* use qlogging message pattern to replace MYNAME.
* first cut at removal of MYNAME.
* add message type support
and massage some logging with internal newlines.
* introduce DebugLog class to transform printf ...
style character output into lines suitable for logging.
* handle debug printing in garmin_gpi
including removal of POSIX printf arguement reordring
* use DebugLog with lowranceusr
* use DebugLog in dg100
* fix logging in garmin_txt
* use DebugLog in exif
* use logging for validate.
* fix includes
* use DebugLog in igc
* use logging in kml
* use logging in garmin
* use DebugLog in mtk.
* use DebugLog in tpo
* use logging in trackfilter
* use DebugLog for v900
* use DebugLog in skytraq
* use logging with nmea.
* fix dg100, update references, chop extra newlines.
* appease MSVC C2131
* fix garmin_gpi address debug messages.
and direct vecs debug output to debug msg.
* fix comparison with testo -D 9 igc format
* match globalsat sport ws debug messages
* match ws on fatal()
* update references for option->stderr and
no extra newline on fatal.
* ws
* don't send empty string to QDebug.
* drop another empty string from logging.
* cleanup fatal, flush is done in message handler.
* move conditional logging check earlier.
* make member functions static
* fix debug build.
* eliminate some QString<->QByteArray round trips.
* purse QStrings from fatal routines.
Besides an efficiency hit any variadic argument strings passed to these
routines should already be in local8Bit.
* rename logging functions for easier script editing.
thanks clion.
* add macro gbLogCStr for use with our logging.
All but one line was changed by sed (ok, the sed script took
a few tries.)
This allows us to change the encoding passed to our printf style
logging routines in one place.
* change logging back to using QStrings.
QtMessageHandler operates on QStrings.
* manual rename logging routines in windows only files.
* use global gbLog instead of DebugLog instances.
* convert all gb printflike logging to accumulate lines.
* use gbDebug instead of gbLog. They are equivalent.
* remove unecessary choping.
* fix getLogString, flush fatal log stream.
* terminate gbFatal format strings with a newline.
Since we flush this isn't necessary, but let's be consistent.
* terminate gbWarning format strings.
* switch to our own MessageHandler for legacy logging.
We don't delay logging until we have a complete line, instead
we output any bits as we go. We only format the log message if
the last output for the first message or if the last output
character was a newline.
* rename LegacyLog components.
* update fatal.cc includes
* use same stream in waypt_status_disp & termination in waypt_disp_session.
stderr is a text stream which should translate '\n' -> '\r\n' on windows
automatically.
* review catches, mostly in comments or dead code.
#include "arcdist.h"
#include <cmath> // for round
-#include <cstdio> // for printf, sscanf
+#include <cstdio> // for sscanf
#include <tuple> // for tie, tuple
#include <QByteArray> // for QByteArray
#if FILTERS_ENABLED
-#define MYNAME "Arc filter"
#define BADVAL 999999
frac = 1.0;
} else {
if (waypointp == nullptr) {
- fatal(FatalMsg() << "Internal error. Attempt to project through a waypoint that doesn't exist");
+ gbFatal(FatalMsg() << "Internal error. Attempt to project through a waypoint that doesn't exist");
}
if (arcpt1 == nullptr) {
- fatal(FatalMsg() << "Internal error: Attempt to project waypoint without predecessor");
+ gbFatal(FatalMsg() << "Internal error: Attempt to project waypoint without predecessor");
}
std::tie(dist, prjpos, frac) = linedistprj(arcpt1->position(),
QString line;
gpsbabel::TextStream stream;
- stream.open(arcfileopt, QIODevice::ReadOnly, MYNAME);
+ stream.open(arcfileopt, QIODevice::ReadOnly);
auto* arcpt1 = new Waypoint;
auto* arcpt2 = new Waypoint;
int argsfound = sscanf(CSTR(line), "%lf %lf", &arcpt2->latitude, &arcpt2->longitude);
if ((argsfound != 2) && (line.trimmed().size() > 0)) {
- warning(MYNAME ": Warning: Arc file contains unusable vertex on line %d.\n", fileline);
+ gbWarning("Warning: Arc file contains unusable vertex on line %d.\n", fileline);
} else {
Waypoint* arcpttmp = arcpt1;
arcdist_arc_disp_wpt_cb(arcpt2);
}
}
if (global_opts.debug_level >= 1) {
- warning("Including waypoint %s at dist:%f lat:%f lon:%f\n",
- qPrintable(wp->shortname), ed->distance, wp->latitude, wp->longitude);
+ gbWarning("Including waypoint %s at dist:%f lat:%f lon:%f\n",
+ gbLogCStr(wp->shortname), ed->distance, wp->latitude, wp->longitude);
}
}
delete ed;
}
del_marked_wpts();
if (global_opts.verbose_status > 0) {
- printf(MYNAME "-arc: %u waypoint(s) removed.\n", removed);
+ gbInfo("%u waypoint(s) removed.\n", removed);
}
}
if ((!arcfileopt && !rteopt && !trkopt) ||
(arcfileopt && (rteopt || trkopt)) ||
(rteopt && trkopt)) {
- fatal(MYNAME ": Incompatible or incomplete option values!\n");
+ gbFatal("Incompatible or incomplete option values!\n");
}
pos_dist = 0.0;
if (distopt) {
- if (parse_distance(distopt, &pos_dist, kMetersPerMile, MYNAME) == 0) {
- fatal(MYNAME ": No distance specified with distance option.\n");
+ if (parse_distance(distopt, &pos_dist, kMetersPerMile) == 0) {
+ gbFatal("No distance specified with distance option.\n");
}
}
}
#include "grtcirc.h" // for RAD, heading_true_degrees, gcdist, linepart, radtometers, DEG
-#define MYNAME "bend"
-
#if FILTERS_ENABLED
void BendFilter::init()
#include "src/core/logging.h" // for Warning
-#define MYNAME "CSV_UTIL"
-
/*********************************************************************/
/* csv_stringclean() - remove any unwanted characters from string. */
/* returns copy of string. */
}
if (enclosed) {
- Warning() << MYNAME":" <<
+ Warning() <<
"Warning- Unbalanced Field Enclosures" <<
enclosed_in <<
"on line" <<
case 'x':
case 'X':
if (index>2) {
- fatal(MYNAME ": too many format specifiers\n");
+ gbFatal("too many format specifiers\n");
}
buff += QString::asprintf(subformat, intvals[index]);
index++;
case 'g':
case 'G':
if (index>2) {
- fatal(MYNAME ": too many format specifiers\n");
+ gbFatal("too many format specifiers\n");
}
buff += QString::asprintf(subformat, dblvals[index]);
index++;
buff += subformat;
break;
default:
- fatal(MYNAME ": invalid format specifier\n");
+ gbFatal("invalid format specifier\n");
break;
}
#include "src/core/datetime.h" // for DateTime
+#define gbLogCStr(qstr) qUtf8Printable(qstr)
#define CSTR(qstr) ((qstr).toUtf8().constData())
#define CSTRc(qstr) ((qstr).toLatin1().constData())
}
}
if (global_opts.verbose_status) {
- fprintf(stdout, "\r\n");
+ // Terminate the progress line from waypt_status_disp.
+ fprintf(stderr, "\n");
+ fflush(stderr);
}
}
#define FF_CAP_RW_WPT \
{ (ff_cap) (ff_cap_read | ff_cap_write), ff_cap_none, ff_cap_none}
-[[noreturn]] void fatal(QDebug& msginstance);
-// cppcheck 2.10.3 fails to assign noreturn attribute to fatal if
+[[noreturn]] void gbFatal(QDebug& msginstance);
+// cppcheck 2.10.3 fails to assign noreturn attribute to gbFatal if
// the noreturn attribute is listed before the gnu::format attribute.
// A PR to resolve this is https://github.com/danmar/cppcheck/pull/4971,
// but cppcheck works if the noreturn attribute follows the gnu::format
// This can have a large effect on codacy issues from cppcheck
// nullPointerRedundantCheck, nullPointerArithmeticRedundantCheck,
// negativeIndex, arrayIndexOutOfBoundsCond.
-[[gnu::format(printf, 1, 2)]] [[noreturn]] void fatal(const char* fmt, ...);
-[[gnu::format(printf, 1, 2)]] void warning(const char* fmt, ...);
+[[gnu::format(printf, 1, 2)]] [[noreturn]] void gbFatal(const char* fmt, ...);
+[[gnu::format(printf, 1, 2)]] void gbWarning(const char* fmt, ...);
+[[gnu::format(printf, 1, 2)]] void gbInfo(const char* fmt, ...);
+[[gnu::format(printf, 1, 2)]] void gbDebug(const char* fmt, ...);
+
+void gbVLegacyLog(QtMsgType type, const char* fmt, va_list args1);
void printposn(double c, bool is_lat);
void xfree(const void* mem);
char* xstrdup(const char* s);
-FILE* xfopen(const QString& fname, const char* type, const QString& errtxt);
+FILE* xfopen(const QString& fname, const char* type);
// Thin wrapper around fopen() that supports Unicode fname on all platforms.
FILE* ufopen(const QString& fname, const char* mode);
int parse_integer(const QString& str, const QString& id, bool* ok = nullptr, QString* end = nullptr, int base = 10);
double parse_double(const QString& str, const QString& id, bool* ok = nullptr, QString* end = nullptr);
int parse_coordinates(const char* str, int datum, grid_type grid,
- double* latitude, double* longitude, const char* module);
+ double* latitude, double* longitude);
int parse_coordinates(const QString& str, int datum, grid_type grid,
- double* latitude, double* longitude, const char* module);
-int parse_distance(const QString& str, double* val, double scale, const char* module);
-int parse_speed(const QString& str, double* val, double scale, const char* module);
+ double* latitude, double* longitude);
+int parse_distance(const QString& str, double* val, double scale);
+int parse_speed(const QString& str, double* val, double scale);
/*
* Color helpers.
#include <cassert> // for assert
#include <cstdarg> // for va_end, va_list, va_start
#include <cstdint> // for uint8_t, uint16_t, int16_t
-#include <cstdio> // for fprintf, stderr, size_t, vfprintf
+#include <cstdio> // for size_t, va_list
#include <cstdlib> // for abs
#include <cstring> // for memcpy, memcmp, strcmp
#include "gbser.h" // for gbser_deinit, gbser_flush, gbser_init, gbser_read_wait, gbser_readc_wait, gbser_set_speed, gbser_write, gbser_ERROR, gbser_OK, gbser_NOTHING
-#define MYNAME "DG-100"
-
const Dg100Format::dg100_command Dg100Format::dg100_commands[] = {
{ dg100cmd_getfile, 2, 1024, 2, "getfile" },
/* the getfileheader answer has variable length, -1 is a dummy value */
/* helper functions */
const Dg100Format::dg100_command*
-Dg100Format::dg100_findcmd(int id) const
+Dg100Format::dg100_findcmd(int id)
{
/* linear search should be OK as long as dg100_numcommands is small */
for (unsigned int i = 0; i < model->numcommands; i++) {
return;
}
- fprintf(stderr, "%s", hdr);
+ gbDebug("%s", hdr);
for (unsigned int i = 0; i < sz; i++) {
- fprintf(stderr, "%02x ", buf[i]);
+ gbDebug("%02x ", buf[i]);
}
if (include_nl) {
- fprintf(stderr, "\n");
+ gbDebug("\n");
}
}
void
Dg100Format::dg100_log(const char* fmt, ...)
{
- va_list ap;
- va_start(ap, fmt);
if (global_opts.debug_level > 0) {
- vfprintf(stderr, fmt, ap);
+ va_list ap;
+ va_start(ap, fmt);
+ gbVLegacyLog(QtDebugMsg, fmt, ap);
+ va_end(ap);
}
- va_end(ap);
}
}
void
-Dg100Format::process_gpsfile(uint8_t data[], route_head** track) const
+Dg100Format::process_gpsfile(uint8_t data[], route_head** track)
{
const int recordsizes[3] = {8, 20, 32};
* determines the format of all subsequent records in the file */
int style = be_read32(data + 28);
if (style > 2) {
- fprintf(stderr, "unknown GPS record style %d", style);
+ gbWarning("unknown GPS record style %d\n", style);
return;
}
int recsize = recordsizes[style];
/* communication functions */
size_t
-Dg100Format::dg100_send(uint8_t cmd, const void* payload, size_t param_len) const
+Dg100Format::dg100_send(uint8_t cmd, const void* payload, size_t param_len)
{
uint8_t frame[FRAME_MAXLEN];
if (isfile) {
QScopedArrayPointer<uint8_t> buf(new uint8_t[framelen]);
if (gbfread(buf.data(), 1, framelen, fin) != framelen) {
- fatal("failed to get data to compare to sent data.\n");
+ gbFatal("failed to get data to compare to sent data.\n");
}
if (memcmp(frame, buf.data(), framelen) != 0) {
- fatal("sent data does not match expected value.\n");
+ gbFatal("sent data does not match expected value.\n");
}
n = gbser_OK;
}
if (n == gbser_ERROR) {
- fatal("dg_100_send: write failed\n");
+ gbFatal("dg_100_send: write failed\n");
}
return (n);
}
int
-Dg100Format::dg100_recv_byte() const
+Dg100Format::dg100_recv_byte()
{
int result;
if (isfile) {
result = gbfgetc(fin);
if (result < 0) {
- fatal("dg100_recv_byte(): read error\n");
+ gbFatal("dg100_recv_byte(): read error\n");
}
} else {
/* allow for a delay of 40s;
result = gbser_readc_wait(serial_handle, 40000);
switch (result) {
case gbser_ERROR:
- fatal("dg100_recv_byte(): error reading one byte\n");
+ gbFatal("dg100_recv_byte(): error reading one byte\n");
case gbser_NOTHING:
- fatal("dg100_recv_byte(): read timeout\n");
+ gbFatal("dg100_recv_byte(): read timeout\n");
}
}
return result;
}
int
-Dg100Format::dg100_read_wait(void* handle, void* buf, unsigned len, unsigned ms) const
+Dg100Format::dg100_read_wait(void* handle, void* buf, unsigned len, unsigned ms)
{
if (isfile) {
return gbfread(buf, 1, len, fin);
* framing around the data), so the caller must copy the data before calling
* this function again */
int
-Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** payload) const
+Dg100Format::dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** payload)
{
static uint8_t buf[FRAME_MAXLEN];
uint16_t payload_end_seq;
/* read Payload Length, Command ID, and two further bytes */
int i = dg100_read_wait(serial_handle, &buf[2], 5, 1000);
if (i < 5) {
- fatal("Expected to read 5 bytes, but got %d\n", i);
+ gbFatal("Expected to read 5 bytes, but got %d\n", i);
}
dg100_debug("", 0, 5, &buf[2]);
if (!cmdinfo) {
/* TODO: consume data until frame end signature,
* then report failure to the caller? */
- fatal("unknown answer ID %02x\n", cmd);
+ gbFatal("unknown answer ID %02x\n", cmd);
}
int param_len = cmdinfo->recvsize;
int frame_len = 2 + 2 + 1 + param_len + ((model->has_payload_end_seq) ? 2 : 0) + 2 + 2;
if (frame_len > FRAME_MAXLEN) {
- fatal("frame too large (frame_len=%d, FRAME_MAXLEN=%d)\n",
+ gbFatal("frame too large (frame_len=%d, FRAME_MAXLEN=%d)\n",
frame_len, FRAME_MAXLEN);
}
i = dg100_read_wait(serial_handle, &buf[7], frame_len - 7, 1000);
if (i < frame_len - 7) {
- fatal("Expected to read %d bytes, but got %d\n",
+ gbFatal("Expected to read %d bytes, but got %d\n",
frame_len - 7, i);
}
dg100_debug("", 0, frame_len - 7, &buf[7]);
/* calculate checksum */
uint16_t sum = dg100_checksum(buf + 4, frame_len - 8);
if (sum != payload_checksum) {
- fatal("checksum mismatch: data sum is 0x%04x, checksum received is 0x%04x\n",
+ gbFatal("checksum mismatch: data sum is 0x%04x, checksum received is 0x%04x\n",
sum, payload_checksum);
}
/* return value: number of bytes copied into buf, -1 on error */
int
-Dg100Format::dg100_recv(uint8_t expected_id, void* buf, unsigned int len) const
+Dg100Format::dg100_recv(uint8_t expected_id, void* buf, unsigned int len)
{
const dg100_command* cmdinfo;
uint8_t* data;
/* check whether the received frame matches the expected answer type */
if (cmdinfo->id != expected_id) {
- fprintf(stderr, "ERROR: answer type %02x, expecting %02x", cmdinfo->id, expected_id);
+ gbWarning("ERROR: answer type %02x, expecting %02x\n", cmdinfo->id, expected_id);
return -1;
}
/* check for buffer overflow */
if (len < copysize) {
- fprintf(stderr, "ERROR: buffer too small, size=%u, need=%u", len, copysize);
+ gbWarning("ERROR: buffer too small, size=%u, need=%u\n", len, copysize);
return -1;
}
/* the number of bytes to be sent is determined by cmd,
* count is the size of recvbuf */
int
-Dg100Format::dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size_t count) const
+Dg100Format::dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size_t count)
{
const dg100_command* cmdinfo = dg100_findcmd(cmd);
assert(cmdinfo != nullptr);
/* higher level communication functions */
QList<int>
-Dg100Format::dg100_getfileheaders() const
+Dg100Format::dg100_getfileheaders()
{
QList<int> headers;
uint8_t request[2];
}
void
-Dg100Format::dg100_getconfig() const
+Dg100Format::dg100_getconfig()
{
uint8_t answer[45];
}
void
-Dg100Format::dg100_getfile(int16_t num, route_head** track) const
+Dg100Format::dg100_getfile(int16_t num, route_head** track)
{
uint8_t request[2];
uint8_t answer[2048];
}
void
-Dg100Format::dg100_getfiles() const
+Dg100Format::dg100_getfiles()
{
route_head* track = nullptr;
}
int
-Dg100Format::dg100_erase() const
+Dg100Format::dg100_erase()
{
uint8_t request[2] = { 0xFF, 0xFF };
uint8_t answer[4];
dg100_request(dg100cmd_erase, request, answer, sizeof(answer));
if (be_read32(answer) != 1) {
- fprintf(stderr, "dg100_erase() FAILED\n");
+ gbWarning("dg100_erase() FAILED\n");
return(-1);
}
return(0);
Dg100Format::common_rd_init(const QString& fname)
{
if (isfile) {
- fin = gbfopen(fname, "rb", MYNAME);
+ fin = gbfopen(fname, "rb");
} else {
if (serial_handle = gbser_init(qPrintable(fname)), nullptr == serial_handle) {
- fatal(MYNAME ": Can't open port '%s'\n", qPrintable(fname));
+ gbFatal("Can't open port '%s'\n", gbLogCStr(fname));
}
if (gbser_set_speed(serial_handle, model->speed) != gbser_OK) {
- fatal(MYNAME ": Can't configure port '%s'\n", qPrintable(fname));
+ gbFatal("Can't configure port '%s'\n", gbLogCStr(fname));
}
// Toss anything that came in before our speed was set, particularly
// for the bluetooth BT-335 product.
/* Member Functions */
- const dg100_command* dg100_findcmd(int id) const;
+ const dg100_command* dg100_findcmd(int id);
static QDateTime bintime2utc(int date, int time);
static void dg100_debug(const char* hdr, int include_nl, size_t sz, unsigned char* buf);
[[gnu::format(printf, 1, 2)]] static void dg100_log(const char* fmt, ...);
static float bin2deg(int val);
- void process_gpsfile(uint8_t* data, route_head** track) const;
+ void process_gpsfile(uint8_t* data, route_head** track);
static uint16_t dg100_checksum(const uint8_t* buf, int count);
- size_t dg100_send(uint8_t cmd, const void* payload, size_t param_len) const;
- int dg100_recv_byte() const;
- int dg100_read_wait(void* handle, void* buf, unsigned int len, unsigned int ms) const;
- int dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** payload) const;
- int dg100_recv(uint8_t expected_id, void* buf, unsigned int len) const;
- int dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size_t count) const;
- QList<int> dg100_getfileheaders() const;
- void dg100_getconfig() const;
- void dg100_getfile(int16_t num, route_head** track) const;
- void dg100_getfiles() const;
- int dg100_erase() const;
+ size_t dg100_send(uint8_t cmd, const void* payload, size_t param_len);
+ int dg100_recv_byte();
+ int dg100_read_wait(void* handle, void* buf, unsigned int len, unsigned int ms);
+ int dg100_recv_frame(const dg100_command** cmdinfo_result, uint8_t** payload);
+ int dg100_recv(uint8_t expected_id, void* buf, unsigned int len);
+ int dg100_request(uint8_t cmd, const void* sendbuf, void* recvbuf, size_t count);
+ QList<int> dg100_getfileheaders();
+ void dg100_getconfig();
+ void dg100_getfile(int16_t num, route_head** track);
+ void dg100_getfiles();
+ int dg100_erase();
void common_rd_init(const QString& fname);
void dg100_rd_init(const QString& fname, bool is_file);
void dg200_rd_init(const QString& fname, bool is_file);
#include <QDebug> // for QDebug
#include <QRegularExpression> // for QRegularExpression, QRegularExpression::CaseInsensitiveOption, QRegularExpressionMatch
-#include "defs.h" // for Waypoint, fatal, route_head (ptr only), del_marked_wpts, route_del_marked_wpts, route_disp_all, track_del_marked_wpts, track_disp_all, waypt_disp_all, fix_none, fix_unknown
+#include "defs.h" // for Waypoint, gbFatal, route_head (ptr only), del_marked_wpts, route_del_marked_wpts, route_disp_all, track_del_marked_wpts, track_disp_all, waypt_disp_all, fix_none, fix_unknown
#include "src/core/logging.h" // for FatalMsg
if (nameopt) {
name_regex = generateRegExp(nameopt);
if (!name_regex.isValid()) {
- fatal(FatalMsg() << "discard: matchname option is an invalid expression.");
+ gbFatal(FatalMsg() << "discard: matchname option is an invalid expression.");
}
}
if (descopt) {
desc_regex = generateRegExp(descopt);
if (!desc_regex.isValid()) {
- fatal(FatalMsg() << "discard: matchdesc option is an invalid expression.");
+ gbFatal(FatalMsg() << "discard: matchdesc option is an invalid expression.");
}
}
if (cmtopt) {
cmt_regex = generateRegExp(cmtopt);
if (!cmt_regex.isValid()) {
- fatal(FatalMsg() << "discard: matchcmt option is an invalid expression.");
+ gbFatal(FatalMsg() << "discard: matchcmt option is an invalid expression.");
}
}
if (iconopt) {
icon_regex = generateRegExp(iconopt);
if (!icon_regex.isValid()) {
- fatal(FatalMsg() << "discard: matchicon option is an invalid expression.");
+ gbFatal(FatalMsg() << "discard: matchicon option is an invalid expression.");
}
}
}
#if FILTERS_ENABLED
-#define MYNAME "duplicate"
-
void DuplicateFilter::init()
{
if (!lcopt && !snopt) {
- fatal(MYNAME ": one or both of the shortname and location options are required.\n");
+ gbFatal("one or both of the shortname and location options are required.\n");
}
}
#include <cfloat> // for DBL_EPSILON
#include <cmath> // for fabs, modf, copysign, round, fmax
#include <cstdint> // for uint32_t, int32_t, uint16_t, int16_t, uint8_t, INT32_MAX
-#include <cstdio> // for printf, SEEK_SET, snprintf, SEEK_CUR
+#include <cstdio> // for SEEK_SET, SEEK_CUR, snprintf
#include <cstdlib> // for abs
#include <cstring> // for memcmp, strlen
#include <utility> // for as_const
-#include "defs.h" // for Waypoint, fatal, warning, global_options, global_opts, unknown_alt, xfree, route_disp_all, track_disp_all, waypt_disp_all, wp_flags, KNOTS_TO_MPS, KPH_TO_MPS, MPH_TO_MPS, MPS_TO_KPH, WAYPT_HAS, case_ignore_strcmp, waypt_add, fix_2d
+#include "defs.h" // for Waypoint, gbFatal, gbWarning, global_options, global_opts, unknown_alt, xfree, route_disp_all, track_disp_all, waypt_disp_all, wp_flags, KNOTS_TO_MPS, KPH_TO_MPS, MPH_TO_MPS, MPS_TO_KPH, WAYPT_HAS, case_ignore_strcmp, waypt_add, fix_2d
#include "garmin_tables.h" // for gt_lookup_datum_index
#include "gbfile.h" // for gbfputuint32, gbfputuint16, gbfgetuint16, gbfgetuint32, gbfseek, gbftell, gbfile, gbfclose, gbfcopyfrom, gbfwrite, gbfopen_be, gbfread, gbfrewind, gbfgetflt, gbfgetint16, gbfopen, gbfputc, gbfputflt, gbsize_t, gbfeof, gbfgetdbl, gbfputdbl, gbfile::(anonymous)
#include "jeeps/gpsmath.h" // for GPS_Math_WGS84_To_Known_Datum_M
#include "src/core/datetime.h" // for DateTime
-#define MYNAME "exif"
-
#define IFD0 0
#define IFD1 1
#define EXIF_IFD 2 /* dummy index */
{
int i;
- printf("%s: ", cmt);
+ gbDebug("%s: ", cmt);
for (i = 0; i < sz; i++) {
- printf("%02x ", buf[i] & 0xFF);
+ gbDebug("%02x ", buf[i] & 0xFF);
}
for (i = 0; i < sz; i++) {
char c = buf[i];
} else if (! isprint(c)) {
c = '.';
}
- printf("%c", c);
+ gbDebug("%c", c);
}
}
break;
default:
- fatal(MYNAME ": Unknown data type %d! Please report.\n", type);
+ gbFatal("Unknown data type %d! Please report.\n", type);
}
return size;
}
while (! gbfeof(fin_)) {
exif_apps->append(new ExifApp);
ExifApp* app = exif_apps->last();
- app->fcache = gbfopen(nullptr, "wb", MYNAME);
+ app->fcache = gbfopen(nullptr, "wb");
app->marker = gbfgetuint16(fin_);
app->len = gbfgetuint16(fin_);
if (global_opts.debug_level >= 3) {
- printf(MYNAME ": api = %02X, len = %u (0x%04x), offs = 0x%08X\n", app->marker & 0xFF, app->len, app->len, gbftell(fin_));
+ gbDebug("api = %02X, len = %u (0x%04x), offs = 0x%08X\n", app->marker & 0xFF, app->len, app->len, gbftell(fin_));
}
if (exif_app_ || (app->marker == 0xFFDA)) { /* compressed data */
gbfcopyfrom(app->fcache, fin_, 0x7FFFFFFF);
if (global_opts.debug_level >= 3) {
- printf(MYNAME ": compressed data size = %u\n", gbftell(app->fcache));
+ gbDebug("compressed data size = %u\n", gbftell(app->fcache));
}
} else {
gbfcopyfrom(app->fcache, fin_, app->len - 2);
name = "private";
break;
}
- printf(MYNAME "-offs 0x%08X: Number of items in IFD%d \"%s\" = %d (0x%04x)\n",
+ gbDebug("offs 0x%08X: Number of items in IFD%d \"%s\" = %d (0x%04x)\n",
offs, ifd_nr, name, ifd->count, ifd->count);
}
if (ifd->count == 0) {
tag->data.append(gbfgetflt(fin));
}
} else {
- fatal(MYNAME "Unknown type %d has size <= 4! Please report.\n", tag->type);
+ gbFatal("Unknown type %d has size <= 4! Please report.\n", tag->type);
}
int skip_bytes = 4 - tag->size;
if (skip_bytes > 0) {
}
}
if (global_opts.debug_level >= 3) {
- printf(MYNAME "-offs 0x%08X: ifd=%d id=0x%04X t=0x%04X c=%4u s=%4u",
+ gbDebug("offs 0x%08X: ifd=%d id=0x%04X t=0x%04X c=%4u s=%4u",
tag->tag_offset, ifd->nr, tag->id, tag->type, tag->count, tag->size);
if (tag->size > 4) {
- printf(" o=0x%08X", tag->offset);
+ gbDebug(" o=0x%08X", tag->offset);
} else {
- printf(" v=0x%02X%02X%02X%02X", tag->raw[0], tag->raw[1], tag->raw[2], tag->raw[3]);
+ gbDebug(" v=0x%02X%02X%02X%02X", tag->raw[0], tag->raw[1], tag->raw[2], tag->raw[3]);
}
if (tag->type == EXIF_TYPE_ASCII) {
QByteArray str = exif_read_str(tag);
- printf(" \"%s\"", str.constData());
+ gbDebug(" \"%s\"", str.constData());
} else {
for (unsigned idx = 0; idx < std::min(tag->count, 4u); ++idx) {
if (tag->type == EXIF_TYPE_BYTE) {
- printf(" %u", tag->data.at(0).toByteArray().at(idx));
+ gbDebug(" %u", tag->data.at(0).toByteArray().at(idx));
} else if (tag->type == EXIF_TYPE_SBYTE) {
- printf(" %d", tag->data.at(0).toByteArray().at(idx));
+ gbDebug(" %d", tag->data.at(0).toByteArray().at(idx));
} else if (tag->type == EXIF_TYPE_UNK) {
- printf(" 0x%02X", tag->data.at(0).toByteArray().at(idx));
+ gbDebug(" 0x%02X", tag->data.at(0).toByteArray().at(idx));
} else if (tag->type == EXIF_TYPE_RAT) {
- printf(" %+#g(%u/%u)", exif_read_double(tag, idx), tag->data.at(idx * 2).value<uint32_t>(), tag->data.at((idx * 2) + 1).value<uint32_t>());
+ gbDebug(" %+#g(%u/%u)", exif_read_double(tag, idx), tag->data.at(idx * 2).value<uint32_t>(), tag->data.at((idx * 2) + 1).value<uint32_t>());
} else if (tag->type == EXIF_TYPE_SRAT) {
- printf(" %+#g(%d/%d)", exif_read_double(tag, idx), tag->data.at(idx * 2).value<int32_t>(), tag->data.at((idx * 2) + 1).value<int32_t>());
+ gbDebug(" %+#g(%d/%d)", exif_read_double(tag, idx), tag->data.at(idx * 2).value<int32_t>(), tag->data.at((idx * 2) + 1).value<int32_t>());
} else if (tag->type == EXIF_TYPE_SHORT) {
- printf(" %u", tag->data.at(idx).value<uint16_t>());
+ gbDebug(" %u", tag->data.at(idx).value<uint16_t>());
} else if (tag->type == EXIF_TYPE_SSHORT) {
- printf(" %d", tag->data.at(idx).value<int16_t>());
+ gbDebug(" %d", tag->data.at(idx).value<int16_t>());
} else if (tag->type == EXIF_TYPE_LONG) {
- printf(" %u", tag->data.at(idx).value<uint32_t>());
+ gbDebug(" %u", tag->data.at(idx).value<uint32_t>());
} else if (tag->type == EXIF_TYPE_SLONG) {
- printf(" %d", tag->data.at(idx).value<int32_t>());
+ gbDebug(" %d", tag->data.at(idx).value<int32_t>());
} else if (tag->type == EXIF_TYPE_FLOAT) {
- printf(" %+#g", tag->data.at(idx).value<float>());
+ gbDebug(" %+#g", tag->data.at(idx).value<float>());
} else if (tag->type == EXIF_TYPE_DOUBLE) {
- printf(" %+#g", tag->data.at(idx).value<double>());
+ gbDebug(" %+#g", tag->data.at(idx).value<double>());
} else {
- printf(" 0x%0*X", 2 * exif_type_size(tag->type), tag->data.at(idx).value<uint32_t>());
+ gbDebug(" 0x%0*X", 2 * exif_type_size(tag->type), tag->data.at(idx).value<uint32_t>());
}
}
if (tag->count > 4) {
- printf(" ...");
+ gbDebug(" ...");
}
}
- printf("\n");
+ gbDebug("\n");
}
#ifndef NDEBUG
exif_validate_tag_structure(tag);
}
if (global_opts.debug_level >= 3) {
- printf(MYNAME "-offs 0x%08X: Next IFD=0x%08X\n", next_ifd_offs, ifd->next_ifd);
+ gbDebug("offs 0x%08X: Next IFD=0x%08X\n", next_ifd_offs, ifd->next_ifd);
}
return ifd;
gbfile* fin = app->fexif;
if (global_opts.debug_level >= 3) {
- printf(MYNAME ": read_app...\n");
- print_buff((const char*)fin->handle.mem, 8, MYNAME "-offs 0x00000000: Image File Header");
- printf("\n");
+ gbDebug("read_app...\n");
+ print_buff((const char*)fin->handle.mem, 8, "offs 0x00000000: Image File Header");
+ gbDebug("\n");
}
exif_ifd_ofs = gps_ifd_ofs = inter_ifd_ofs = 0;
gbfrewind(ftmp);
uint32_t ident = gbfgetuint32(ftmp);
if (ident != 0x66697845) {
- fatal(MYNAME ": Invalid EXIF header magic.");
+ gbFatal("Invalid EXIF header magic.\n");
}
if (gbfgetint16(ftmp) != 0) {
- fatal(MYNAME ": Error in EXIF header.");
+ gbFatal("Error in EXIF header.\n");
}
uint16_t endianness = gbfgetint16(ftmp);
if (global_opts.debug_level >= 3) {
- printf(MYNAME ": endianness = 0x%04X\n", endianness);
+ gbDebug("endianness = 0x%04X\n", endianness);
}
if (endianness == 0x4949) {
ftmp->big_endian = 0;
} else if (endianness == 0x4D4D) {
ftmp->big_endian = 1;
} else {
- fatal(MYNAME ": Invalid endianness identifier 0x%04X!\n", endianness);
+ gbFatal("Invalid endianness identifier 0x%04X!\n", endianness);
}
gbfseek(ftmp, 6, SEEK_SET);
- app->fexif = gbfopen(nullptr, "wb", MYNAME);
+ app->fexif = gbfopen(nullptr, "wb");
app->fexif->big_endian = ftmp->big_endian;
gbfcopyfrom(app->fexif, ftmp, 0x7FFFFFFF);
}
QDateTime
-ExifFormat::exif_get_exif_time(ExifApp* app) const
+ExifFormat::exif_get_exif_time(ExifApp* app)
{
QDateTime res;
} else if (opt_offsettime) {
// Only warn for user supplied offsets.
// Offset tags may indicate the offset was unknown, e.g. " : ".
- warning(MYNAME ": OffsetTime is expected to be +HH:MM or -HH:MM, but was %s.\n", qPrintable(time_tag));
+ gbWarning("OffsetTime is expected to be +HH:MM or -HH:MM, but was %s.\n", gbLogCStr(time_tag));
}
}
}
Waypoint*
-ExifFormat::exif_waypt_from_exif_app(ExifApp* app) const
+ExifFormat::exif_waypt_from_exif_app(ExifApp* app)
{
ExifTag* tag;
char lat_ref = '\0';
}
if ((wpt->latitude == unknown_alt) || (wpt->longitude == unknown_alt)) {
- fatal(MYNAME ": Missing GPSLatitude and/or GPSLongitude!\n");
+ gbFatal("Missing GPSLatitude and/or GPSLongitude!\n");
}
if (lat_ref == 'S') {
wpt->latitude *= -1;
} else if (lat_ref != 'N') {
- warning(MYNAME ": GPSLatitudeRef not set! Using N(orth).\n");
+ gbWarning("GPSLatitudeRef not set! Using N(orth).\n");
}
if (lon_ref == 'W') {
wpt->longitude *= -1;
} else if (lon_ref != 'E') {
- warning(MYNAME ": GPSLongitudeRef not set! Using E(ast).\n");
+ gbWarning("GPSLongitudeRef not set! Using E(ast).\n");
}
if (global_opts.debug_level >= 3) {
- printf(MYNAME "-GPSLatitude = %12.7f\n", wpt->latitude);
- printf(MYNAME "-GPSLongitude = %12.7f\n", wpt->longitude);
+ gbDebug("GPSLatitude = %12.7f\n", wpt->latitude);
+ gbDebug("GPSLongitude = %12.7f\n", wpt->longitude);
}
if (!datum.isEmpty()) {
- int idatum = gt_lookup_datum_index(datum, MYNAME);
+ int idatum = gt_lookup_datum_index(datum);
if (idatum < 0) {
- fatal(MYNAME ": Unknown GPSMapDatum \"%s\"!\n", datum.constData());
+ gbFatal("Unknown GPSMapDatum \"%s\"!\n", datum.constData());
}
if (idatum != kDatumWGS84) {
GPS_Math_WGS84_To_Known_Datum_M(wpt->latitude, wpt->longitude, 0.0,
break;
default:
- warning(MYNAME ": Invalid GPSAltitudeRef (%d)! Using default value 0 (= Sea level).\n", alt_ref);
+ gbWarning("Invalid GPSAltitudeRef (%d)! Using default value 0 (= Sea level).\n", alt_ref);
sign = 1.0;
}
wpt->altitude = sign * alt;
if (global_opts.debug_level >= 3) {
- printf(MYNAME "-GPSAltitude = %12.7f m\n", wpt->altitude);
+ gbDebug("GPSAltitude = %12.7f m\n", wpt->altitude);
}
}
break;
default:
wpt->reset_speed();
- warning(MYNAME ": Unknown GPSSpeedRef unit %c (0x%02x)!\n", speed_ref, speed_ref);
+ gbWarning("Unknown GPSSpeedRef unit %c (0x%02x)!\n", speed_ref, speed_ref);
}
if (global_opts.debug_level >= 3) {
if (wpt->speed_has_value()) {
- printf(MYNAME "-GPSSpeed = %12.2f m/s\n", wpt->speed_value());
+ gbDebug("GPSSpeed = %12.2f m/s\n", wpt->speed_value());
}
}
}
gps_datetime = QDateTime(datestamp, timestamp, QtUTC);
if (gps_datetime.isValid()) {
if (global_opts.debug_level >= 3) {
- printf(MYNAME "-GPSTimeStamp = %s\n", qPrintable(gps_datetime.toString(Qt::ISODateWithMs)));
+ gbDebug("GPSTimeStamp = %s\n", gbLogCStr(gps_datetime.toString(Qt::ISODateWithMs)));
}
wpt->SetCreationTime(gps_datetime);
} else {
if (pval < lower_limit) {
return Rational<int32_t>(0, upper_limit);
} else if (pval > upper_limit) {
- fatal(MYNAME ": Value (%f) to big for a rational representation!\n", val);
+ gbFatal("Value (%f) to big for a rational representation!\n", val);
return Rational<int32_t>(copysign(upper_limit, val), 1);
}
}
ExifFormat::ExifTag*
-ExifFormat::exif_put_value(const int ifd_nr, const uint16_t tag_id, const uint16_t type, const int count, const int index, const void* data) const
+ExifFormat::exif_put_value(const int ifd_nr, const uint16_t tag_id, const uint16_t type, const int count, const int index, const void* data)
{
ExifTag* tag = nullptr;
uint16_t size;
double val = *static_cast<const double*>(data);
if ((val < 0.0) && (type == EXIF_TYPE_RAT)) {
- fatal(MYNAME ": A negative value cannot be stored as type RATIONAL.");
+ gbFatal("A negative value cannot be stored as type RATIONAL.\n");
}
Rational<int32_t> rat = exif_dec2frac(val, 1e-11);
tag->data[index] = *static_cast<const double*>(data);
break;
default:
- fatal(MYNAME ": Unknown data type %u!\n", type);
+ gbFatal("Unknown data type %u!\n", type);
}
}
return tag;
void
-ExifFormat::exif_put_double(const int ifd_nr, const int tag_id, const int index, const double val) const
+ExifFormat::exif_put_double(const int ifd_nr, const int tag_id, const int index, const double val)
{
// TODO: It seems wrong to throw away the sign.
double d = fabs(val);
void
-ExifFormat::exif_put_str(const int ifd_nr, const int tag_id, const char* val) const
+ExifFormat::exif_put_str(const int ifd_nr, const int tag_id, const char* val)
{
int len = (val) ? strlen(val) + 1 : 0;
exif_put_value(ifd_nr, tag_id, EXIF_TYPE_ASCII, len, 0, val);
}
void
-ExifFormat::exif_put_coord(const int ifd_nr, const int tag_id, const double val) const
+ExifFormat::exif_put_coord(const int ifd_nr, const int tag_id, const double val)
{
double vdeg;
double vmin;
}
void
-ExifFormat::exif_put_long(const int ifd_nr, const int tag_id, const int index, const int32_t val) const
+ExifFormat::exif_put_long(const int ifd_nr, const int tag_id, const int index, const int32_t val)
{
exif_put_value(ifd_nr, tag_id, EXIF_TYPE_LONG, 1, index, &val);
}
void
-ExifFormat::exif_put_short(const int ifd_nr, const int tag_id, const int index, const int16_t val) const
+ExifFormat::exif_put_short(const int ifd_nr, const int tag_id, const int index, const int16_t val)
{
exif_put_value(ifd_nr, tag_id, EXIF_TYPE_SHORT, 1, index, &val);
}
void
-ExifFormat::exif_remove_tag(const int ifd_nr, const int tag_id) const
+ExifFormat::exif_remove_tag(const int ifd_nr, const int tag_id)
{
exif_put_value(ifd_nr, tag_id, EXIF_TYPE_BYTE, 0, 0, nullptr);
}
gbfputflt(tag->data.at(0).value<float>(), fout);
}
} else {
- fatal(MYNAME ": Unknown data type %d or wrong tag size %d!\n", tag->type, tag->size);
+ gbFatal("Unknown data type %d or wrong tag size %d!\n", tag->type, tag->size);
}
int fill_bytes = 4 - tag->size;
for (int idx = 0; idx < fill_bytes; ++idx) {
}
void
-ExifFormat::exif_write_apps() const
+ExifFormat::exif_write_apps()
{
gbfputuint16(0xFFD8, fout_);
// IFD1_TAG_COMPRESSION should be 6 indicating JPEG compressed image data.
tag_size = exif_find_tag(app, IFD1, IFD1_TAG_JPEG_SIZE);
if (tag_size == nullptr) {
- fatal(MYNAME ": Invalid image file, in IFD1 both JPEGInterchangeFormat and JPEGInterchangeFormatLength must exist for compressed thumbnails.");
+ gbFatal("Invalid image file, in IFD1 both JPEGInterchangeFormat and JPEGInterchangeFormatLength must exist for compressed thumbnails.\n");
}
auto offset = tag_offset->data.at(0).value<uint32_t>();
auto size = tag_size->data.at(0).value<uint32_t>();
// IFD1_TAG_COMPRESSION should be 1 indicating uncompressed image data.
tag_size = exif_find_tag(app, IFD1, IFD1_TAG_STRIP_BYTE_COUNTS);
if ((tag_size == nullptr) || (tag_size->count != tag_offset->count)) {
- fatal(MYNAME ": Invalid image file, in IFD1 both StripOffsets and StripByteCounts must exist and have equal counts for uncompressed thumbnails.");
+ gbFatal("Invalid image file, in IFD1 both StripOffsets and StripByteCounts must exist and have equal counts for uncompressed thumbnails.\n");
}
for (unsigned idx = 0; idx < tag_offset->count; idx++) {
auto offset = tag_offset->data.at(idx).value<uint32_t>();
std::sort(ifd->tags.begin(), ifd->tags.end(), exif_sort_tags_cb);
}
- gbfile* ftmp = gbfopen_be(nullptr, "wb", MYNAME);
+ gbfile* ftmp = gbfopen_be(nullptr, "wb");
ftmp->big_endian = app->fcache->big_endian;
gbfwrite((ftmp->big_endian) ? "MM" : "II", 2, 1, ftmp);
void
ExifFormat::rd_init(const QString& fname)
{
- fin_ = gbfopen_be(fname, "rb", MYNAME);
+ fin_ = gbfopen_be(fname, "rb");
exif_apps = new QList<ExifApp*>;
}
uint16_t soi = gbfgetuint16(fin_);
/* only jpeg for now */
if (soi != 0xFFD8) {
- fatal(MYNAME ": Unknown image file.");
+ gbFatal("Unknown image file.\n");
}
exif_app_ = exif_load_apps();
if (exif_app_ == nullptr) {
- fatal(MYNAME ": No EXIF header in source file \"%s\".", qPrintable(fin_->name));
+ gbFatal("No EXIF header in source file \"%s\".\n", gbLogCStr(fin_->name));
}
exif_examine_app(exif_app_);
exif_apps = new QList<ExifApp*>;
- fin_ = gbfopen_be(fname, "rb", MYNAME);
+ fin_ = gbfopen_be(fname, "rb");
if (fin_->is_pipe) {
- fatal(MYNAME ": Sorry, this format cannot be used with pipes!");
+ gbFatal("Sorry, this format cannot be used with pipes!\n");
}
uint16_t soi = gbfgetuint16(fin_);
if (soi != 0xFFD8) {
- fatal(MYNAME ": Unknown image file.");
+ gbFatal("Unknown image file.\n");
}
exif_app_ = exif_load_apps();
if (exif_app_ == nullptr) {
- fatal(MYNAME ": No EXIF header found in source file \"%s\".", qPrintable(fin_->name));
+ gbFatal("No EXIF header found in source file \"%s\".\n", gbLogCStr(fin_->name));
}
exif_examine_app(exif_app_);
gbfclose(fin_);
exif_time_ref = exif_get_exif_time(exif_app_);
if (!exif_time_ref.isValid()) {
- fatal(MYNAME ": No valid timestamp found in picture!\n");
+ gbFatal("No valid timestamp found in picture!\n");
}
QString filename(fname);
filename += ".jpg";
- fout_ = gbfopen_be(filename, "wb", MYNAME);
+ fout_ = gbfopen_be(filename, "wb");
}
void
track_disp_all(nullptr, nullptr, exif_find_wpt_by_name_lambda);
}
if (exif_wpt_ref == nullptr) {
- warning(MYNAME ": No matching point with name \"%s\" found.\n", qPrintable(opt_name));
+ gbWarning("No matching point with name \"%s\" found.\n", gbLogCStr(opt_name));
}
} else {
auto exif_find_wpt_by_time_lambda = [this](const Waypoint* waypointp)->void {
qint64 frame = opt_frame.get_result();
if (exif_wpt_ref == nullptr) {
- warning(MYNAME ": No point with a valid timestamp found.\n");
+ gbWarning("No point with a valid timestamp found.\n");
} else if (std::abs(exif_time_ref.secsTo(exif_wpt_ref->creation_time)) > frame) {
QString time_str = exif_time_str(exif_time_ref);
- warning(MYNAME ": No matching point found for image date %s!\n", qPrintable(time_str));
+ gbWarning("No matching point found for image date %s!\n", gbLogCStr(time_str));
if (exif_wpt_ref != nullptr) {
QString str = exif_time_str(exif_wpt_ref->creation_time);
- warning(MYNAME ": Best is from %s, %lld second(s) away.\n",
- qPrintable(str), std::abs(exif_time_ref.secsTo(exif_wpt_ref->creation_time)));
+ gbWarning("Best is from %s, %lld second(s) away.\n",
+ gbLogCStr(str), std::abs(exif_time_ref.secsTo(exif_wpt_ref->creation_time)));
}
exif_wpt_ref = nullptr;
}
static void exif_examine_app(ExifApp* app);
static ExifIfd* exif_find_ifd(ExifApp* app, uint16_t ifd_nr);
static ExifTag* exif_find_tag(ExifApp* app, uint16_t ifd_nr, uint16_t tag_id);
- QDateTime exif_get_exif_time(ExifApp* app) const;
- Waypoint* exif_waypt_from_exif_app(ExifApp* app) const;
+ QDateTime exif_get_exif_time(ExifApp* app);
+ Waypoint* exif_waypt_from_exif_app(ExifApp* app);
static Rational<int> exif_dec2frac(double val, double tolerance);
- ExifTag* exif_put_value(int ifd_nr, uint16_t tag_id, uint16_t type, int count, int index, const void* data) const;
- void exif_put_double(int ifd_nr, int tag_id, int index, double val) const;
- void exif_put_str(int ifd_nr, int tag_id, const char* val) const;
- void exif_put_coord(int ifd_nr, int tag_id, double val) const;
- void exif_put_long(int ifd_nr, int tag_id, int index, int32_t val) const;
- void exif_put_short(int ifd_nr, int tag_id, int index, int16_t val) const;
- void exif_remove_tag(int ifd_nr, int tag_id) const;
+ ExifTag* exif_put_value(int ifd_nr, uint16_t tag_id, uint16_t type, int count, int index, const void* data);
+ void exif_put_double(int ifd_nr, int tag_id, int index, double val);
+ void exif_put_str(int ifd_nr, int tag_id, const char* val);
+ void exif_put_coord(int ifd_nr, int tag_id, double val);
+ void exif_put_long(int ifd_nr, int tag_id, int index, int32_t val);
+ void exif_put_short(int ifd_nr, int tag_id, int index, int16_t val);
+ void exif_remove_tag(int ifd_nr, int tag_id);
void exif_find_wpt_by_time(const Waypoint* wpt);
void exif_find_wpt_by_name(const Waypoint* wpt);
static bool exif_sort_tags_cb(const ExifTag& A, const ExifTag& B);
static bool exif_sort_ifds_cb(const ExifIfd& A, const ExifIfd& B);
static void exif_write_value(ExifTag* tag, gbfile* fout);
static void exif_write_ifd(ExifIfd* ifd, char next, gbfile* fout);
- void exif_write_apps() const;
+ void exif_write_apps();
/* Data Members */
/*
Functions to indicate inconsistent or fatal conditions.
- Copyright (C) 2002-2014 Robert Lipe, robertlipe+source@gpsbabel.org
+ Copyright (C) 2002-2014,2024 Robert Lipe, robertlipe+source@gpsbabel.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
*/
#include <cstdarg> // for va_end, va_list, va_start
-#include <cstdio> // for vfprintf, stderr, fflush, fprintf, stdout
+#include <cstdio> // for fprintf, stderr, fflush
#include <cstdlib> // for exit
-#include "defs.h" // for Fatal, debug_print, fatal, warning
+#include <QDebug> // for QDebug
+#include <QMessageLogContext> // for QtMsgType, QMessageLogContext, qFormatLogMessage
+#include <QString> // for QString
+#include <QtGlobal> // for qPrintable
+
+#include "defs.h" // for gbFatal, gbDebug, gbInfo, gbVLegacyLog, gbWarning
#include "src/core/logging.h" // for FatalMsg
+#ifdef PIGS_FLY
+static QByteArray xvasprintf(const char* fmt, va_list args)
+{
+ va_list args2;
+ va_copy(args2, args);
+ auto cbufsz = 1 + vsnprintf(nullptr, 0, fmt, args);
+ char* cbuf = new char[cbufsz];
+ vsnprintf(cbuf, cbufsz, fmt, args2);
+ va_end(args2);
+ QByteArray rval(cbuf);
+ delete[] cbuf;
+ return rval;
+}
+#endif
-[[noreturn]] void fatal(QDebug& msginstance)
+[[noreturn]] void gbFatal(QDebug& msginstance)
{
auto* myinstance = new FatalMsg;
myinstance->swap(msginstance);
}
[[noreturn]] void
-fatal(const char* fmt, ...)
+gbFatal(const char* fmt, ...)
{
- /* flush any buffered standard output */
- fflush(stdout);
-
- va_list ap;
- va_start(ap, fmt);
- vfprintf(stderr, fmt, ap);
- va_end(ap);
+ va_list args;
+ va_start(args, fmt);
+ gbVLegacyLog(QtCriticalMsg, fmt, args);
+ va_end(args);
exit(1);
}
void
-warning(const char* fmt, ...)
+gbWarning(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ gbVLegacyLog(QtWarningMsg, fmt, args);
+ va_end(args);
+}
+
+void
+gbInfo(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ gbVLegacyLog(QtInfoMsg, fmt, args);
+ va_end(args);
+}
+
+void
+gbDebug(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ gbVLegacyLog(QtDebugMsg, fmt, args);
+ va_end(args);
+}
+
+static void LegacyLogMessageHandler(QtMsgType type, const QString& msg)
{
- va_list ap;
- va_start(ap, fmt);
- vfprintf(stderr, fmt, ap);
- va_end(ap);
+ static bool lineInProgress = false;
+
+ if (lineInProgress) {
+ fprintf(stderr, "%s", qPrintable(msg));
+ } else {
+ QString message = qFormatLogMessage(type, QMessageLogContext(), msg);
+ fprintf(stderr, "%s", qPrintable(message));
+ }
+ fflush(stderr);
+
+ lineInProgress = !msg.endsWith('\n');
+}
+
+void gbVLegacyLog(QtMsgType type, const char* fmt, va_list args)
+{
+ QString logString(QString::vasprintf(fmt, args));
+
+ for (auto idx = logString.indexOf('\n'); idx >= 0; idx = logString.indexOf('\n')) {
+ QString msg = logString.sliced(0, idx + 1);
+ LegacyLogMessageHandler(type, msg);
+ logString.remove(0, idx + 1);
+ }
+ if (!logString.isEmpty()) {
+ LegacyLogMessageHandler(type, logString);
+ }
}
#include "arcdist.h" // for ArcDistanceFilter
#include "bend.h" // for BendFilter
-#include "defs.h" // for arglist_t, CSTR, xfree, ARGTYPE_HIDDEN, fatal, global_options, global_opts, ARGTYPE_REQUIRED
+#include "defs.h" // for arglist_t, CSTR, xfree, ARGTYPE_HIDDEN, gbFatal, global_options, global_opts, ARGTYPE_REQUIRED
#include "discard.h" // for DiscardFilter
#include "duplicate.h" // for DuplicateFilter
#include "filter.h" // for Filter
{
QStringList options = fltargstring.split(',');
if (options.isEmpty()) {
- fatal("A filter name is required.\n");
+ gbFatal("A filter name is required.\n");
}
const QString fltname = options.takeFirst();
virtual void rd_init(const QString& /* fname */)
{
- fatal("Format does not support reading.\n");
-// fin = gbfopen(fname, "r", MYNAME);
+ gbFatal("Format does not support reading.\n");
+// fin = gbfopen(fname, "r");
}
virtual void rd_deinit()
virtual void wr_init(const QString& /* fname */)
{
- fatal("Format does not support writing.\n");
-// fout = gbfopen(fname, "w", MYNAME);
+ gbFatal("Format does not support writing.\n");
+// fout = gbfopen(fname, "w");
}
virtual void wr_deinit()
virtual void rd_position_init(const QString& /* fname */)
{
- fatal("Realtime tracking (-T) is not supported by this input type.\n");
+ gbFatal("Realtime tracking (-T) is not supported by this input type.\n");
}
virtual Waypoint* rd_position(posn_status* /* status */)
virtual void wr_position(Waypoint* /* wpt */)
{
- fatal("This output format does not support output of realtime positioning.\n");
+ gbFatal("This output format does not support output of realtime positioning.\n");
}
virtual void wr_position_deinit()
#include "defs.h"
-#define MYNAME "format_skeleton"
-
// Any arg in this list will appear in command line help and will be
// populated for you.
static void
format_skeleton_rd_init(const char* fname)
{
-// fin = gbfopen(fname, "r", MYNAME);
+// fin = gbfopen(fname, "r");
}
static void
static void
format_skeleton_wr_init(const char* fname)
{
-// fout = gbfopen(fname, "w", MYNAME);
+// fout = gbfopen(fname, "w");
}
static void
#include <climits> // for INT_MAX
#include <cmath> // for atan2, modf, sqrt
-#include <cstdio> // for fprintf, fflush, snprintf, snprintf
+#include <cstdio> // for snprintf, size_t
#include <cstdint> // for int32_t
#include <cstring> // for memcpy, strlen, strncpy, strchr
#include <ctime> // for time_t
#include "mkshort.h" // for MakeShort
-#define MYNAME "GARMIN"
-
#define MILITANT_VALID_WAYPT_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
case 115200:
break;
default:
- fatal("Baud rate %d is not supported\n", baud);
+ gbFatal("Baud rate %d is not supported\n", baud);
}
}
if (GPS_Init(qPrintable(fname)) < 0) {
- fatal(MYNAME ":Can't init %s\n", qPrintable(fname));
+ gbFatal("Can't init %s\n", gbLogCStr(fname));
}
/*
switch (gps_waypt_type) { /* waypoint type as defined by jeeps */
case 0:
- fatal("Garmin unit %d does not support waypoint xfer.",
+ gbFatal("Garmin unit %d does not support waypoint xfer.\n",
gps_save_id);
break;
}
if (global_opts.debug_level > 0) {
- fprintf(stderr, "Waypoint type: %d\n"
- "Chosen waypoint length %d\n",
- gps_waypt_type, receiver_short_length);
+ gbDebug("Waypoint type: %d\n", gps_waypt_type);
+ gbDebug("Chosen waypoint length %d\n", receiver_short_length);
if (gps_category_type) {
- fprintf(stderr, "Waypoint category type: %d\n",
- gps_category_type);
+ gbDebug("Waypoint category type: %d\n", gps_category_type);
}
}
}
codec = get_codec(receiver_charset);
if (global_opts.verbose_status) {
- fprintf(stdout, "receiver charset detected as %s.\r\n", receiver_charset.constData());
+ gbInfo("receiver charset detected as %s.\n", receiver_charset.constData());
}
valid_chars = valid_waypt_chars;
}
if ((n = GPS_Command_Get_Waypoint(portname, &way, waypt_read_cb)) < 0) {
- fatal(MYNAME ":Can't get waypoint from %s\n", portname);
+ gbFatal("Can't get waypoint from %s\n", portname);
}
for (int i = 0; i < n; i++) {
* error, do it now.
*/
if (gps_errno) {
- fatal(MYNAME ": Fatal error reading position.\n");
+ gbFatal("Fatal error reading position.\n");
}
delete wpt;
}
if (!(global_opts.masked_objective &
(WPTDATAMASK | TRKDATAMASK | RTEDATAMASK | POSNDATAMASK))) {
- fatal(MYNAME ": Nothing to do.\n");
+ gbFatal("Nothing to do.\n");
}
}
{
GPS_PWay way = GPS_Way_New();
if (!way) {
- fatal(MYNAME ":not enough memory\n");
+ gbFatal("not enough memory\n");
}
/*
int n = waypoint_prepare();
if (int32_t ret = GPS_Command_Send_Waypoint(portname, tx_waylist, n, waypt_write_cb); ret < 0) {
- fatal(MYNAME ":communication error sending waypoints..\n");
+ gbFatal("communication error sending waypoints..\n");
}
for (int i = 0; i < n; ++i) {
GPS_Way_Del(&tx_waylist[i]);
}
if (global_opts.verbose_status) {
- fprintf(stdout, "\r\n");
- fflush(stdout);
+ gbInfo("\n");
}
xfree(tx_waylist);
}
#include "src/core/logging.h" // for Warning, Fatal
-#define MYNAME "fit"
-
/*******************************************************************************
* %%% global callbacks called by gpsbabel main process %%% *
*******************************************************************************/
void
GarminFitFormat::rd_init(const QString& fname)
{
- fin = gbfopen_le(fname, "rb", MYNAME);
+ fin = gbfopen_le(fname, "rb");
}
void
void
GarminFitFormat::wr_init(const QString& fname)
{
- fout = gbfopen_le(fname, "w+b", MYNAME);
+ fout = gbfopen_le(fname, "w+b");
}
void
int len = gbfgetc(fin);
if (len == EOF || len < 12) {
- fatal(MYNAME ": Bad header\n");
+ gbFatal("Bad header\n");
}
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": header len=" << len;
+ Debug(1) << "header len=" << len;
}
int ver = gbfgetc(fin);
if (ver == EOF || (ver >> 4) > 2)
- fatal(MYNAME ": Unsupported protocol version %d.%d\n",
+ gbFatal("Unsupported protocol version %d.%d\n",
ver >> 4, ver & 0xf);
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": protocol version=" << ver;
+ Debug(1) << "protocol version=" << ver;
}
// profile version
fit_data.len = gbfgetuint32(fin);
// File signature
if (gbfread(sig, 4, 1, fin) != 1) {
- fatal(MYNAME ": Unexpected end of file\n");
+ gbFatal("Unexpected end of file\n");
}
if (sig[0] != '.' || sig[1] != 'F' || sig[2] != 'I' || sig[3] != 'T') {
- fatal(MYNAME ": .FIT signature missing\n");
+ gbFatal(".FIT signature missing\n");
}
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": profile version=" << ver;
- Debug(1) << MYNAME ": fit_data.len=" << fit_data.len;
+ Debug(1) << "profile version=" << ver;
+ Debug(1) << "fit_data.len=" << fit_data.len;
}
// Header CRC may be omitted entirely
for (unsigned int i = 0; i < kReadHeaderCrcLen; ++i) {
int data = gbfgetc(fin);
if (data == EOF) {
- fatal(MYNAME ": File %s truncated\n", qPrintable(fin->name));
+ gbFatal("File %s truncated\n", gbLogCStr(fin->name));
}
crc = fit_crc16(data, crc);
}
if (crc != 0) {
- Warning().nospace() << MYNAME ": Header CRC mismatch in file " << fin->name << ".";
+ Warning().nospace() << "Header CRC mismatch in file " << fin->name << ".";
if (!opt_recoverymode) {
- fatal(FatalMsg().nospace() << MYNAME ": File " << fin->name << " is corrupt. Use recoverymode option at your risk.");
+ gbFatal(FatalMsg().nospace() << "File " << fin->name << " is corrupt. Use recoverymode option at your risk.");
}
} else if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": Header CRC verified.";
+ Debug(1) << "Header CRC verified.";
}
}
}
QFileInfo fi(fin->name);
qint64 size = fi.size();
if ((len + fit_data.len + 2) != size) {
- Warning().nospace() << MYNAME ": File size " << size << " is not expected given header len " << len << ", data length " << fit_data.len << " and a 2 byte file CRC.";
+ Warning().nospace() << "File size " << size << " is not expected given header len " << len << ", data length " << fit_data.len << " and a 2 byte file CRC.";
} else if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": File size matches expectations from information in the header.";
+ Debug(1) << "File size matches expectations from information in the header.";
}
gbfseek(fin, len, SEEK_SET);
// byte 5 has the number of records in the remainder of the definition message
int num_fields = fit_getuint8();
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": definition message contains " << num_fields << " records";
+ Debug(8) << "definition message contains " << num_fields << " records";
}
// remainder of the definition message is data at one byte per field * 3 fields
int type = fit_getuint8();
fit_field_t field = {id, size, type};
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": record " << i << " ID: " << field.id << " SIZE: "
+ Debug(8) << "record " << i << " ID: " << field.id << " SIZE: "
<< field.size << " TYPE: " << field.type << " fit_data.len="
<< fit_data.len;
}
if (hasDevFields) {
int numOfDevFields = fit_getuint8();
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": definition message contains " << numOfDevFields << " developer records";
+ Debug(8) << "definition message contains " << numOfDevFields << " developer records";
}
if (numOfDevFields > 0) {
int numOfFields = num_fields + numOfDevFields;
int type = fit_getuint8();
fit_field_t field = {id, size, type};
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": developer record " << i - num_fields <<
+ Debug(8) << "developer record " << i - num_fields <<
" ID: " << field.id << " SIZE: " << field.size <<
" TYPE: " << field.type << " fit_data.len=" << fit_data.len;
}
// otherwise we just skip over the data.
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": fit_read_field: read data field with f.type=0x" <<
+ Debug(8) << "fit_read_field: read data field with f.type=0x" <<
Qt::hex << f.type << " and f.size=" <<
Qt::dec << f.size << " fit_data.len=" << fit_data.len;
}
fit_getuint8();
}
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": fit_read_field: skipping 1-byte array data";
+ Debug(8) << "fit_read_field: skipping 1-byte array data";
}
return -1;
}
fit_getuint8();
}
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": fit_read_field: skipping 2-byte array data";
+ Debug(8) << "fit_read_field: skipping 2-byte array data";
}
return -1;
}
fit_getuint8();
}
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": fit_read_field: skipping 4-byte array data";
+ Debug(8) << "fit_read_field: skipping 4-byte array data";
}
return -1;
}
fit_getuint8();
}
if (global_opts.debug_level >= 8) {
- Debug(8) << MYNAME ": fit_read_field: skipping unrecognized data type";
+ Debug(8) << "fit_read_field: skipping unrecognized data type";
}
return -1;
}
QString description;
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data ID " << def.global_id << " with num_fields=" << def.fields.size();
+ Debug(7) << "parsing fit data ID " << def.global_id << " with num_fields=" << def.fields.size();
}
for (int i = 0; i < def.fields.size(); ++i) {
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing field " << i;
+ Debug(7) << "parsing field " << i;
}
const fit_field_t& f = def.fields.at(i);
QVariant field = fit_read_field(f);
}
if (f.id == kFieldTimestamp) {
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: timestamp=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: timestamp=" << static_cast<int32_t>(val);
}
timestamp = val;
// if the timestamp is < 0x10000000, this value represents
switch (f.id) {
case kFieldGlobalUtcOffset:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: global utc_offset=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: global utc_offset=" << static_cast<int32_t>(val);
}
fit_data.global_utc_offset = val;
break;
default:
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT device settings: f.id=" << f.id;
+ Debug(1) << "unrecognized data type in GARMIN FIT device settings: f.id=" << f.id;
}
break;
} // switch (f.id)
switch (f.id) {
case kFieldLatitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: lat=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: lat=" << static_cast<int32_t>(val);
}
lat = val;
break;
case kFieldLongitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: lon=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: lon=" << static_cast<int32_t>(val);
}
lon = val;
break;
case kFieldAltitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: alt=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: alt=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
alt = val;
break;
case kFieldHeartRate:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: heartrate=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: heartrate=" << static_cast<int32_t>(val);
}
heartrate = val;
break;
case kFieldCadence:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: cadence=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: cadence=" << static_cast<int32_t>(val);
}
cadence = val;
break;
case kFieldDistance:
// NOTE: 5 is DISTANCE in cm ... unused.
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": unrecognized data type in GARMIN FIT record: f.id=" << f.id;
+ Debug(7) << "unrecognized data type in GARMIN FIT record: f.id=" << f.id;
}
break;
case kFieldSpeed:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: speed=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: speed=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
speed = val;
break;
case kFieldPower:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: power=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: power=" << static_cast<int32_t>(val);
}
power = val;
break;
case kFieldTemperature:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: temperature=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: temperature=" << static_cast<int32_t>(val);
}
temperature = val;
break;
case kFieldEnhancedSpeed:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: enhanced_speed=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: enhanced_speed=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
speed = val;
break;
case kFieldEnhancedAltitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: enhanced_altitude=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: enhanced_altitude=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
alt = val;
break;
default:
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT record: f.id=" << f.id;
+ Debug(1) << "unrecognized data type in GARMIN FIT record: f.id=" << f.id;
}
break;
} // switch (f.id)
switch (f.id) {
case kFieldStartTime:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: starttime=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: starttime=" << static_cast<int32_t>(val);
}
//starttime = val;
break;
case kFieldStartLatitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: startlat=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: startlat=" << static_cast<int32_t>(val);
}
//startlat = val;
break;
case kFieldStartLongitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: startlon=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: startlon=" << static_cast<int32_t>(val);
}
//startlon = val;
break;
case kFieldEndLatitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: endlat=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: endlat=" << static_cast<int32_t>(val);
}
endlat = val;
break;
case kFieldEndLongitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: endlon=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: endlon=" << static_cast<int32_t>(val);
}
endlon = val;
break;
case kFieldElapsedTime:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: elapsedtime=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: elapsedtime=" << static_cast<int32_t>(val);
}
//elapsedtime = val;
break;
case kFieldTotalDistance:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: totaldistance=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: totaldistance=" << static_cast<int32_t>(val);
}
//totaldistance = val;
break;
default:
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT lap: f.id=" << f.id;
+ Debug(1) << "unrecognized data type in GARMIN FIT lap: f.id=" << f.id;
}
break;
} // switch (f.id)
switch (f.id) {
case kFieldEvent:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: event=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: event=" << static_cast<int32_t>(val);
}
event = val;
break;
case kFieldEventType:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: eventtype=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: eventtype=" << static_cast<int32_t>(val);
}
eventtype = val;
break;
switch (f.id) {
case kFieldLocLatitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: lat=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: lat=" << static_cast<int32_t>(val);
}
lat = val;
break;
case kFieldLocLongitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: lon=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: lon=" << static_cast<int32_t>(val);
}
lon = val;
break;
case kFieldLocAltitude:
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: alt=" << static_cast<int32_t>(val);
+ Debug(7) << "parsing fit data: alt=" << static_cast<int32_t>(val);
}
if (val != 0xffff) {
alt = val;
case kFieldLocationName:
name = field.toString();
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: location name=" << name;
+ Debug(7) << "parsing fit data: location name=" << name;
}
break;
case kFieldLocationDescription:
description = field.toString();
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": parsing fit data: location description=" << description;
+ Debug(7) << "parsing fit data: location description=" << description;
}
break;
default:
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": unrecognized data type in GARMIN FIT locations: f.id=" << f.id;
+ Debug(1) << "unrecognized data type in GARMIN FIT locations: f.id=" << f.id;
}
break;
} // switch (f.id)
break;
default:
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": unrecognized/unhandled global ID for GARMIN FIT: " << def.global_id;
+ Debug(1) << "unrecognized/unhandled global ID for GARMIN FIT: " << def.global_id;
}
break;
} // switch (def.global_id)
}
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": storing fit data with num_fields=" << def.fields.size();
+ Debug(7) << "storing fit data with num_fields=" << def.fields.size();
}
switch (def.global_id) {
case kIdLap: { // lap message
break;
}
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": storing fit data LAP " << def.global_id;
+ Debug(7) << "storing fit data LAP " << def.global_id;
}
auto* lappt = new Waypoint;
lappt->latitude = GPS_Math_Semi_To_Deg(endlat);
break;
}
if (global_opts.debug_level >= 7) {
- Debug(7) << MYNAME ": storing fit data location " << def.global_id;
+ Debug(7) << "storing fit data location " << def.global_id;
}
auto* locpt = new Waypoint;
locpt->latitude = GPS_Math_Semi_To_Deg(lat);
// bits 3..0 -> local message type
if (header & 0x80) {
if (global_opts.debug_level >= 6) {
- Debug(6) << MYNAME ": got compressed message at file position 0x" <<
+ Debug(6) << "got compressed message at file position 0x" <<
Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len
<< " ...local message type 0x" << Qt::hex << (header & 0x0f);
}
fit_parse_compressed_message(header);
} else if (header & 0x40) {
if (global_opts.debug_level >= 6) {
- Debug(6) << MYNAME ": got definition message at file position 0x" <<
+ Debug(6) << "got definition message at file position 0x" <<
Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len
<< " ...local message type 0x" << Qt::hex << (header & 0x0f);
}
fit_parse_definition_message(header);
} else {
if (global_opts.debug_level >= 6) {
- Debug(6) << MYNAME ": got data message at file position 0x" <<
+ Debug(6) << "got data message at file position 0x" <<
Qt::hex << position << ", fit_data.len=" << Qt::dec << fit_data.len
<< " ...local message type 0x" << Qt::hex << (header & 0x0f);
}
crc = fit_crc16(data, crc);
}
if (crc != 0) {
- Warning().nospace() << MYNAME ": File CRC mismatch in file " << fin->name << ".";
+ Warning().nospace() << "File CRC mismatch in file " << fin->name << ".";
if (!opt_recoverymode) {
- fatal(FatalMsg().nospace() << MYNAME ": File " << fin->name << " is corrupt. Use recoverymode option at your risk.");
+ gbFatal(FatalMsg().nospace() << "File " << fin->name << " is corrupt. Use recoverymode option at your risk.");
}
} else if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": File CRC verified.";
+ Debug(1) << "File CRC verified.";
}
gbfseek(fin, position, SEEK_SET);
fit_data.track = new route_head;
track_add_head(fit_data.track);
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME ": starting to read data with fit_data.len=" << fit_data.len;
+ Debug(1) << "starting to read data with fit_data.len=" << fit_data.len;
}
try {
while (fit_data.len) {
}
} catch (ReaderException& e) {
if (opt_recoverymode) {
- warning(MYNAME ": %s\n",e.what());
- warning(MYNAME ": Aborting read and continuing processing.\n");
+ gbWarning("%s\n",e.what());
+ gbWarning("Aborting read and continuing processing.\n");
} else {
- fatal(MYNAME ": %s Use recoverymode option at your risk.\n",e.what());
+ gbFatal("%s Use recoverymode option at your risk.\n",e.what());
}
}
}
// Update data records size in file header
gbsize_t file_size = gbftell(fout);
if (file_size < kWriteHeaderCrcLen) {
- fatal(MYNAME ": File %s truncated\n", qPrintable(fout->name));
+ gbFatal("File %s truncated\n", gbLogCStr(fout->name));
}
gbfseek(fout, 0, SEEK_SET);
fit_write_file_header(file_size - kWriteHeaderCrcLen, 0);
for (unsigned int i = 0; i < kWriteHeaderLen; ++i) {
int data = gbfgetc(fout);
if (data == EOF) {
- fatal(MYNAME ": File %s truncated\n", qPrintable(fout->name));
+ gbFatal("File %s truncated\n", gbLogCStr(fout->name));
}
crc = fit_crc16(data, crc);
}
#include "jeeps/gpsmath.h" // for GPS_Math_Deg_To_Semi, GPS_Math_Semi_To_Deg
-#define MYNAME "garmin_gpi"
-
#define DEFAULT_ICON "Waypoint"
#define WAYPOINTS_PER_BLOCK 128
#define GPI_BITMAP_SIZE sizeof(gpi_bitmap)
#define GPI_DBG global_opts.debug_level >= 3
-#define PP if (GPI_DBG) warning("@%1$6x (%1$8d): ", gbftell(fin))
+#define PP if (GPI_DBG) gbDebug("@%6x (%8d): ", gbftell(fin), gbftell(fin))
/*******************************************************************************
* %%% gpi reader %%% *
GarminGPIFormat::gpi_gmsd_init(Waypoint* wpt)
{
if (wpt == nullptr) {
- fatal(MYNAME ": Error in file structure.\n");
+ gbFatal("Error in file structure.\n");
}
garmin_fs_t* gmsd = garmin_fs_t::find(wpt);
if (gmsd == nullptr) {
}
GarminGPIFormat::lc_string
-GarminGPIFormat::gpi_read_lc_string() const
+GarminGPIFormat::gpi_read_lc_string()
{
lc_string result;
gbfread(result.lc.data(), 1, 2, fin);
if ((result.lc.at(0) < 'A') || (result.lc.at(0) > 'Z') ||
(result.lc.at(1) < 'A') || (result.lc.at(1) > 'Z')) {
- fatal(MYNAME ": Invalid language code %s!\n", result.lc.constData());
+ gbFatal("Invalid language code %s!\n", result.lc.constData());
}
result.strlen = gbfgetint16(fin);
/* read a standard string with or without 'EN' (or whatever) header */
QString
-GarminGPIFormat::gpi_read_string(const char* field) const
+GarminGPIFormat::gpi_read_string(const char* field)
{
QByteArray string;
if (first == 0) {
if (gbfgetc(fin) != 0) {
- fatal(MYNAME ": Error reading field '%s'!", field);
+ gbFatal("Error reading field '%s'!\n", field);
}
lc_string res1 = gpi_read_lc_string();
if ((res1.strlen + 4) < l0) { // dual language?
lc_string res2 = gpi_read_lc_string();
if (res1.strlen + 4 + res2.strlen + 4 != l0) {
- fatal(MYNAME ": Error out of sync (wrong size %d/%d/%d) on field '%s'!", l0, res1.strlen, res2.strlen, field);
+ gbFatal("Error out of sync (wrong size %d/%d/%d) on field '%s'!\n", l0, res1.strlen, res2.strlen, field);
}
if (opt_lang && (opt_lang.get().toUtf8() == res1.lc)) {
string = res1.str;
} else if (opt_lang && (opt_lang.get().toUtf8() == res2.lc)) {
string = res2.str;
} else {
- fatal(MYNAME ": Must select language code, %s and %s found.\n", res1.lc.constData(), res2.lc.constData());
+ gbFatal("Must select language code, %s and %s found.\n", res1.lc.constData(), res2.lc.constData());
}
} else { // normal case, single language
if (res1.strlen + 4 != l0) {
- fatal(MYNAME ": Error out of sync (wrong size %d/%d) on field '%s'!", l0, res1.strlen, field);
+ gbFatal("Error out of sync (wrong size %d/%d) on field '%s'!\n", l0, res1.strlen, field);
}
string = res1.str;
}
QString result = str_to_unicode(string).trimmed();
if (GPI_DBG) {
- warning("%s: \"%s\"\n", field, result.isNull() ? "<NULL>" : qPrintable(result));
+ gbDebug("%s: \"%s\"\n", field, result.isNull() ? "<NULL>" : gbLogCStr(result));
}
return result;
}
gbfread(&rdata->S3, 1, sizeof(rdata->S3) - 1, fin); /* GRMRECnn */
if (strncmp(rdata->S3, "GRMREC", 6) != 0) {
- fatal(MYNAME ": No GPI file!\n");
+ gbFatal("No GPI file!\n");
}
PP;
rdata->crdate = gbfgetint32(fin);
if (GPI_DBG) {
time_t crdate = GPS_Math_Gtime_To_Utime(rdata->crdate);
- warning("crdate = %lld (%s)\n", (long long) rdata->crdate,
+ gbDebug("crdate = %lld (%s)\n", (long long) rdata->crdate,
CSTR(QDateTime::fromSecsSinceEpoch(crdate, QtUTC).toString(Qt::ISODate)));
}
gbfread(&rdata->POI, 1, sizeof(rdata->POI) - 1, fin);
if (strncmp(rdata->POI, "POI", 3) != 0) {
- fatal(MYNAME ": Wrong or unsupported GPI file!\n");
+ gbFatal("Wrong or unsupported GPI file!\n");
}
for (i = 0; i < 3; i++) {
codepage = gbfgetuint16(fin);
if (GPI_DBG) {
PP;
- warning("Code Page: %d\n",codepage);
+ gbDebug("Code Page: %d\n",codepage);
}
(void) gbfgetint16(fin); /* typically 0, but 0x11 in
Garminonline.de files. */
if (GPI_DBG) {
PP;
- warning("< leaving header\n");
+ gbDebug("< leaving header\n");
}
}
{
if (GPI_DBG) {
PP;
- warning("> reading poi (size %d)\n", sz);
+ gbDebug("> reading poi (size %d)\n", sz);
}
PP;
int len = 0;
len = gbfgetint32(fin); /* sub-header size */
}
if (GPI_DBG) {
- warning("poi sublen = %d (0x%x)\n", len, len);
+ gbDebug("poi sublen = %d (0x%x)\n", len, len);
}
(void) len;
int pos = gbftell(fin);
if (GPI_DBG) {
PP;
- warning("< leaving poi\n");
+ gbDebug("< leaving poi\n");
}
}
int pos = gbftell(fin);
if (GPI_DBG) {
PP;
- warning("> reading poi list (-> %x / %d )\n", pos + sz, pos + sz);
+ gbDebug("> reading poi list (-> %x / %d )\n", pos + sz, pos + sz);
}
PP;
int i = gbfgetint32(fin); /* mostly 23 (0x17) */
if (GPI_DBG) {
- warning("list sublen = %d (0x%x)\n", i, i);
+ gbDebug("list sublen = %d (0x%x)\n", i, i);
}
(void) i;
}
if (GPI_DBG) {
PP;
- warning("< leaving poi list\n");
+ gbDebug("< leaving poi list\n");
}
}
int pos = gbftell(fin);
if (GPI_DBG) {
PP;
- warning("> reading poi group (-> %x / %d)\n", pos + sz, pos + sz);
+ gbDebug("> reading poi group (-> %x / %d)\n", pos + sz, pos + sz);
}
if (tag == 0x80009) {
PP;
int subsz = gbfgetint32(fin); /* ? offset to category data ? */
if (GPI_DBG) {
- warning("group sublen = %d (-> %x / %d)\n", subsz, pos + subsz + 4, pos + subsz + 4);
+ gbDebug("group sublen = %d (-> %x / %d)\n", subsz, pos + subsz + 4, pos + subsz + 4);
}
(void)subsz;
}
if (GPI_DBG) {
PP;
- warning("< leaving poi group\n");
+ gbDebug("< leaving poi group\n");
}
}
if (GPI_DBG) {
PP;
- warning("%s: tag = 0x%x (size %d)\n", caller, tag, sz);
+ gbDebug("%s: tag = 0x%x (size %d)\n", caller, tag, sz);
}
if ((tag >= 0x80000) && (tag <= 0x800ff)) {
sz += 4;
PP;
mask = gbfgetint16(fin); /* address fields mask */
if (GPI_DBG) {
- warning("GPI Address field mask: %d (0x%02x)\n", mask, mask);
+ gbDebug("GPI Address field mask: %d (0x%02x)\n", mask, mask);
}
if ((mask & GPI_ADDR_CITY) && !(str = gpi_read_string("City")).isEmpty()) {
gmsd = gpi_gmsd_init(wpt);
mask = gbfgetint16(fin); /* phone fields mask */
if (GPI_DBG) {
- warning("GPI Phone field mask: %d (0x%02x)\n", mask, mask);
+ gbDebug("GPI Phone field mask: %d (0x%02x)\n", mask, mask);
}
if ((mask & 1) && !(str = gpi_read_string("Phone")).isEmpty()) {
gmsd = gpi_gmsd_init(wpt);
if (GPI_DBG) {
int x;
std::unique_ptr<unsigned char[]> b(new unsigned char[sz]);
- fprintf(stderr, "Tag: %x\n", tag);
+ gbDebug("Tag: %x\n", tag);
gbfread(b.get(), 1, sz, fin);
- fprintf(stderr, "\n");
+ gbDebug("\n");
for (x = 0; x < sz; x++) {
- fprintf(stderr, "%02x ", b[x]);
+ gbDebug("%02x ", b[x]);
}
- fprintf(stderr, "\n");
+ gbDebug("\n");
for (x = 0; x < sz; x++) {
- fprintf(stderr, "%c", isalnum(b[x]) ? b[x] : '.');
+ gbDebug("%c", isalnum(b[x]) ? b[x] : '.');
}
- fprintf(stderr, "\n");
+ gbDebug("\n");
}
break;
default:
- warning(MYNAME ": Unknown tag (0x%x). Please report!\n", tag);
+ gbWarning("Unknown tag (0x%x). Please report!\n", tag);
return 0;
}
gbfseek(fin, pos + sz, SEEK_SET);
scale = KPH_TO_MPS(1);
}
double speed = 0;
- parse_speed(wpt->shortname.mid(pidx + 1), &speed, scale, MYNAME);
+ parse_speed(wpt->shortname.mid(pidx + 1), &speed, scale);
if (speed > 0) {
wpt->set_speed(speed);
}
gpi_bitmap_header_t* dest_h;
unsigned char* ptr;
- gbfile* f = gbfopen_le(fname, "rb", MYNAME);
+ gbfile* f = gbfopen_le(fname, "rb");
if (gbfgetint16(f) != 0x4d42) {
- fatal(MYNAME ": No BMP image.");
+ gbFatal("No BMP image.\n");
}
/* read a standard bmp file header */
}
if (GPI_DBG) {
- printf("data size: 0x%x (%d)\n", src_h.size, src_h.size);
- printf("image data offset: 0x%x (%d)\n", src_h.image_offset, src_h.image_offset);
- printf("header size: 0x%x (%d)\n", src_h.header_size, src_h.header_size);
- printf("image width: 0x%x (%d)\n", src_h.width, src_h.width);
- printf("image height: 0x%x (%d)\n", src_h.height, src_h.height);
- printf("number of planes: 0x%x (%d)\n", src_h.planes, src_h.planes);
- printf("bits per pixel: 0x%x (%d)\n", src_h.bpp, src_h.bpp);
- printf("compression type: 0x%x (%d)\n", src_h.compression_type, src_h.compression_type);
- printf("image size: 0x%x (%d)\n", src_h.image_data_size, src_h.image_data_size);
- printf("horizontal resolution: 0x%x (%d)\n", src_h.resolution_h, src_h.resolution_h);
- printf("vertical resolution: 0x%x (%d)\n", src_h.resolution_v, src_h.resolution_v);
- printf("number of colors: 0x%x (%d)\n", src_h.used_colors, src_h.used_colors);
- printf("important colors: 0x%x (%d)\n", src_h.important_colors, src_h.important_colors);
+ gbDebug("data size: 0x%x (%d)\n", src_h.size, src_h.size);
+ gbDebug("image data offset: 0x%x (%d)\n", src_h.image_offset, src_h.image_offset);
+ gbDebug("header size: 0x%x (%d)\n", src_h.header_size, src_h.header_size);
+ gbDebug("image width: 0x%x (%d)\n", src_h.width, src_h.width);
+ gbDebug("image height: 0x%x (%d)\n", src_h.height, src_h.height);
+ gbDebug("number of planes: 0x%x (%d)\n", src_h.planes, src_h.planes);
+ gbDebug("bits per pixel: 0x%x (%d)\n", src_h.bpp, src_h.bpp);
+ gbDebug("compression type: 0x%x (%d)\n", src_h.compression_type, src_h.compression_type);
+ gbDebug("image size: 0x%x (%d)\n", src_h.image_data_size, src_h.image_data_size);
+ gbDebug("horizontal resolution: 0x%x (%d)\n", src_h.resolution_h, src_h.resolution_h);
+ gbDebug("vertical resolution: 0x%x (%d)\n", src_h.resolution_v, src_h.resolution_v);
+ gbDebug("number of colors: 0x%x (%d)\n", src_h.used_colors, src_h.used_colors);
+ gbDebug("important colors: 0x%x (%d)\n", src_h.important_colors, src_h.important_colors);
}
/* sort out unsupported files */
if (!((src_h.width <= 24) && (src_h.height <= 24) &&
(src_h.width > 0) && (src_h.height > 0))) {
- fatal(MYNAME ": Unsupported format (%dx%d)!\n", src_h.width, src_h.height);
+ gbFatal("Unsupported format (%dx%d)!\n", src_h.width, src_h.height);
}
if (!((src_h.bpp == 8) || (src_h.bpp == 24) || (src_h.bpp == 32))) {
- fatal(MYNAME ": Unsupported color depth (%d)!\n", src_h.bpp);
+ gbFatal("Unsupported color depth (%d)!\n", src_h.bpp);
}
if (!(src_h.compression_type == 0)) {
- fatal(MYNAME ": Sorry, we don't support compressed bitmaps.\n");
+ gbFatal("Sorry, we don't support compressed bitmaps.\n");
}
std::unique_ptr<uint32_t[]> color_table;
} else if (str.startsWith('s', Qt::CaseInsensitive)) {
result = 's';
} else {
- fatal(MYNAME ": Unknown units parameter (%s).\n", qPrintable(str));
+ gbFatal("Unknown units parameter (%s).\n", gbLogCStr(str));
}
return result;
}
void
GarminGPIFormat::rd_init(const QString& fname)
{
- fin = gbfopen_le(fname, "rb", MYNAME);
+ fin = gbfopen_le(fname, "rb");
rdata = new reader_data_t;
read_header();
} else if (codepage == 65001) {
codec = get_codec("utf8");
} else {
- fatal(MYNAME ": Unsupported code page (%d). File is likely encrypted.\n", codepage);
+ gbFatal("Unsupported code page (%d). File is likely encrypted.\n", codepage);
}
units = parse_units(opt_units);
gpi_timestamp = gpsbabel_time;
}
- fout = gbfopen_le(fname, "wb", MYNAME);
+ fout = gbfopen_le(fname, "wb");
short_h = new MakeShort;
}
if (! codepage) {
- warning(MYNAME ": Unsupported character set (%s)!\n", qPrintable(opt_writecodec));
- fatal(MYNAME ": Valid values are windows-1250 to windows-1257 and utf8.\n");
+ gbWarning("Unsupported character set (%s)!\n", gbLogCStr(opt_writecodec));
+ gbFatal("Valid values are windows-1250 to windows-1257 and utf8.\n");
}
codec = get_codec(opt_writecodec.get().toUtf8());
} else {
scale = KPH_TO_MPS(1);
}
- parse_speed(opt_speed, &defspeed, scale, MYNAME);
+ parse_speed(opt_speed, &defspeed, scale);
}
if (opt_proximity) {
} else {
scale = 1000.0; /* one kilometer in meters */
}
- parse_distance(opt_proximity, &defproximity, scale, MYNAME);
+ parse_distance(opt_proximity, &defproximity, scale);
}
wdata = wdata_alloc();
}
int image_sz;
if (opt_cat.isEmpty()) {
- fatal(MYNAME ": Can't write empty category!\n");
+ gbFatal("Can't write empty category!\n");
}
if (opt_hide_bitmap) {
/* Member Functions */
static garmin_fs_t* gpi_gmsd_init(Waypoint* wpt);
- lc_string gpi_read_lc_string() const;
- QString gpi_read_string(const char* field) const;
+ lc_string gpi_read_lc_string();
+ QString gpi_read_string(const char* field);
void read_header();
void read_poi(int sz, int tag);
void read_poi_list(int sz);
#include "jeeps/gpsmath.h" // for GPS_Lookup_Datum_Index, GPS_Math_Get_Datum_Name
#include "src/core/logging.h" // for Fatal
-#define MYNAME "garmin_tables"
-
// these tables are in an include file so they can be shared with mkicondoc.
#include "garmin_icon_tables.h" // for garmin_icon_table, garmin_smart_icon_table
}
break;
default:
- fatal(MYNAME ": unknown garmin format.\n");
+ gbFatal("unknown garmin format.\n");
}
}
return DEFAULT_ICON_DESCR;
case GARMIN_SERIAL:
return icon_mapping.pcxsymnum;
default:
- fatal(MYNAME ": unknown garmin format.\n");
+ gbFatal("unknown garmin format.\n");
}
}
}
case GARMIN_SERIAL:
return icon_mapping.pcxsymnum;
default:
- fatal(MYNAME ": unknown garmin format.\n");
+ gbFatal("unknown garmin format.\n");
}
}
}
}
grid_type
-gt_lookup_grid_type(const QString& grid_name, const QString& module)
+gt_lookup_grid_type(const QString& grid_name)
{
for (const auto& grid_mapping : gt_mps_grid_names) {
if (QString::compare(grid_name, grid_mapping.shortname, Qt::CaseInsensitive) == 0 ||
}
}
- fatal(FatalMsg().nospace().noquote() << module <<
- ": Unsupported grid (" << grid_name <<
+ gbFatal(FatalMsg().nospace().noquote() <<
+ "Unsupported grid (" << grid_name <<
"). See GPSBabel help for supported grids.");
return grid_unknown; /* (warnings) */
}
QString
-gt_get_mps_grid_longname(const grid_type grid, const QString& module)
+gt_get_mps_grid_longname(const grid_type grid)
{
if ((grid < GRID_INDEX_MIN) || (grid > GRID_INDEX_MAX)) {
- fatal(FatalMsg().nospace().noquote() << module <<
- ": Grid index out of range " << grid <<
+ gbFatal(FatalMsg().nospace().noquote() <<
+ "Grid index out of range " << grid <<
" (" << GRID_INDEX_MIN << ".." << GRID_INDEX_MAX << ")!");
}
return gt_mps_grid_names[grid].longname;
}
int
-gt_lookup_datum_index(const QString& datum_str, const QString& module)
+gt_lookup_datum_index(const QString& datum_str)
{
QString name = datum_str;
}
if (result < 0) {
- fatal(FatalMsg().nospace().noquote() << module <<
- ": Unsupported datum (" << datum_str <<
+ gbFatal(FatalMsg().nospace().noquote() <<
+ "Unsupported datum (" << datum_str <<
"). See GPSBabel help for supported datums.");
}
return result;
unsigned char gt_switch_display_mode_value(unsigned char display_mode, int protoid, char device);
-grid_type gt_lookup_grid_type(const QString& grid_name, const QString& module);
-QString gt_get_mps_grid_longname(grid_type grid, const QString& module);
-int gt_lookup_datum_index(const QString& datum_str, const QString& module);
+grid_type gt_lookup_grid_type(const QString& grid_name);
+QString gt_get_mps_grid_longname(grid_type grid);
+int gt_lookup_datum_index(const QString& datum_str);
QString gt_get_mps_datum_name(int datum_index);
uint32_t gt_color_value(unsigned int garmin_index);
uint32_t gt_color_value_by_name(const QString& name);
#include <cctype> // for toupper
#include <cmath> // for fabs, floor
#include <cstdint> // for uint16_t
-#include <cstdio> // for sscanf, fprintf, snprintf, stderr
+#include <cstdio> // for snprintf, sscanf
#include <cstdlib> // for abs
#include <cstring> // for strstr, strlen
#include <ctime> // for gmtime, time_t, localtime, strftime, tm
#include "src/core/textstream.h" // for TextStream
-#define MYNAME "garmin_txt"
-
const QVector<QString> GarminTxtFormat::headers = {
"Name\tDescription\tType\tPosition\tAltitude\tDepth\tProximity\tTemperature\t"
"Display Mode\tColor\tSymbol\tFacility\tCity\tState\tCountry\t"
break;
default:
- fatal("ToDo\n");
+ gbFatal("ToDo\n");
}
if (! valid) {
*fout << "#####\n";
- fatal(MYNAME ": %s (%s) is outside of convertible area \"%s\"!\n",
- wpt->shortname.isEmpty() ? "Waypoint" : qPrintable(wpt->shortname),
- qPrintable(pretty_deg_format(wpt->latitude, wpt->longitude, 'd', nullptr, false)),
- qPrintable(gt_get_mps_grid_longname(grid_index, MYNAME)));
+ gbFatal("%s (%s) is outside of convertible area \"%s\"!\n",
+ wpt->shortname.isEmpty() ? "Waypoint" : gbLogCStr(wpt->shortname),
+ gbLogCStr(pretty_deg_format(wpt->latitude, wpt->longitude, 'd', nullptr, false)),
+ gbLogCStr(gt_get_mps_grid_longname(grid_index)));
}
}
}
if (time_only) {
tm = *gmtime(&time);
- snprintf(tbuf, sizeof(tbuf), "%d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec);
- *fout << QString::asprintf("%s", tbuf);
+ *fout << QString::asprintf("%d:%02d:%02d", tm.tm_hour, tm.tm_min, tm.tm_sec);
} else if (time != 0) {
if (gtxt_flags.utc) {
time_t t = time + utc_offs;
gtxt_flags = {};
fout = new gpsbabel::TextStream;
- fout->open(fname, QIODevice::WriteOnly, MYNAME, "windows-1252");
+ fout->open(fname, QIODevice::WriteOnly, "windows-1252");
gtxt_flags.metric = opt_dist.get().startsWith("m", Qt::CaseInsensitive);
gtxt_flags.celsius = opt_temp.get().startsWith("c", Qt::CaseInsensitive);
if (opt_precision) {
precision = opt_precision.get_result();
if (precision < 0) {
- fatal(MYNAME ": Invalid precision (%s)!", qPrintable(opt_precision));
+ gbFatal("Invalid precision (%s)!\n", gbLogCStr(opt_precision));
}
}
if (int i = opt_grid.toInt(&ok); ok) {
grid_index = (grid_type) i;
if ((grid_index < GRID_INDEX_MIN) || (grid_index > GRID_INDEX_MAX))
- fatal(MYNAME ": Grid index out of range (%d..%d)!\n",
+ gbFatal("Grid index out of range (%d..%d)!\n",
(int)GRID_INDEX_MIN, (int)GRID_INDEX_MAX);
} else {
- grid_index = gt_lookup_grid_type(opt_grid, MYNAME);
+ grid_index = gt_lookup_grid_type(opt_grid);
}
}
datum_index = kDatumWGS84;
break;
default:
- datum_index = gt_lookup_datum_index(opt_datum, MYNAME);
+ datum_index = gt_lookup_datum_index(opt_datum);
}
garmin_txt_utc_option();
track_disp_wpt_cb(waypointp);
};
- QString grid_str = gt_get_mps_grid_longname(grid_index, MYNAME);
+ QString grid_str = gt_get_mps_grid_longname(grid_index);
grid_str = grid_str.replace('*', u'°');
*fout << "Grid\t" << grid_str << "\r\n";
q += "AP";
continue;
default:
- warning(MYNAME ": omitting unknown strptime conversion \"%%%c\" in \"%s\"\n", s[i], s);
+ gbWarning("omitting unknown strptime conversion \"%%%c\" in \"%s\"\n", s[i], s);
break;
}
}
QString cin = catstring.trimmed();
if (!cin.isEmpty()) {
if (std::optional<uint16_t> cat = garmin_fs_t::convert_category(cin); !cat.has_value()) {
- warning(MYNAME ": Unable to convert category \"%s\" at line %d!\n", qPrintable(cin), current_line);
+ gbWarning("Unable to convert category \"%s\" at line %d!\n", gbLogCStr(cin), current_line);
} else {
res = res | *cat;
}
*temperature = FAHRENHEIT_TO_CELSIUS(value);
break;
default:
- fatal(MYNAME ": Unknown temperature unit \"%c\" at line %d!\n", unit, current_line);
+ gbFatal("Unknown temperature unit \"%c\" at line %d!\n", unit, current_line);
}
return true;
} else {
- fatal(MYNAME ": Invalid temperature \"%s\" at line %d!\n", qPrintable(str), current_line);
+ gbFatal("Invalid temperature \"%s\" at line %d!\n", gbLogCStr(str), current_line);
}
return false;
}
return true;
}
}
- warning(MYNAME ": Unknown display mode \"%s\" at line %d.\n", qPrintable(str), current_line);
+ gbWarning("Unknown display mode \"%s\" at line %d.\n", gbLogCStr(str), current_line);
return false;
}
GarminTxtFormat::bind_fields(const header_type ht)
{
if ((grid_index < 0) || (datum_index < 0)) {
- fatal(MYNAME ": Incomplete or invalid file header!");
+ gbFatal("Incomplete or invalid file header!\n");
}
if (header_column_names.isEmpty()) {
int field_no = field_idx + 1;
header_mapping_info[ht].append(std::make_pair(name, field_no));
if (global_opts.debug_level >= 2) {
- fprintf(stderr, MYNAME ": Binding field \"%s\" to internal number %d (%d,%d)\n", qPrintable(name), field_no, ht, i);
+ gbDebug("Binding field \"%s\" to internal number %d (%d,%d)\n", gbLogCStr(name), field_no, ht, i);
}
} else {
- warning(MYNAME ": Field %s not recognized!\n", qPrintable(name));
+ gbWarning("Field %s not recognized!\n", gbLogCStr(name));
}
}
header_column_names.clear();
GarminTxtFormat::parse_grid(const QStringList& lineparts)
{
if (lineparts.empty()) {
- fatal(MYNAME ": Missing grid headline!\n");
+ gbFatal("Missing grid headline!\n");
}
const QString str = lineparts.at(0);
} else if (str.contains("mm'ss.s")) {
grid_index = grid_lat_lon_dms;
} else {
- grid_index = gt_lookup_grid_type(str, MYNAME);
+ grid_index = gt_lookup_grid_type(str);
}
}
GarminTxtFormat::parse_datum(const QStringList& lineparts)
{
if (lineparts.empty()) {
- fatal(MYNAME ": Missing GPS datum headline!\n");
+ gbFatal("Missing GPS datum headline!\n");
}
const auto& str = lineparts.at(0);
- datum_index = gt_lookup_datum_index(str, MYNAME);
+ datum_index = gt_lookup_datum_index(str);
}
void
for (const auto& str : lineparts) {
if (++column >= header_mapping_info[waypt_header].size()) {
- warning(MYNAME ": too many fields in Waypoint record!\n");
+ gbWarning("too many fields in Waypoint record!\n");
break;
}
int i;
break;
case 4:
parse_coordinates(str, datum_index, grid_index,
- &wpt->latitude, &wpt->longitude, MYNAME);
+ &wpt->latitude, &wpt->longitude);
break;
case 5:
- if (parse_distance(str, &d, 1, MYNAME)) {
+ if (parse_distance(str, &d, 1)) {
wpt->altitude = d;
}
break;
case 6:
- if (parse_distance(str, &d, 1, MYNAME)) {
+ if (parse_distance(str, &d, 1)) {
wpt->set_depth(d);
}
break;
case 7:
- if (parse_distance(str, &d, 1, MYNAME)) {
+ if (parse_distance(str, &d, 1)) {
wpt->set_proximity(d);
}
break;
bind_fields(route_header);
for (const auto& str : lineparts) {
if (++column >= header_mapping_info[route_header].size()) {
- warning(MYNAME ": too many fields in Route record!\n");
+ gbWarning("too many fields in Route record!\n");
break;
}
const auto& [name, field_no] = header_mapping_info[route_header].at(column);
auto* trk = new route_head;
for (const auto& str : lineparts) {
if (++column >= header_mapping_info[track_header].size()) {
- warning(MYNAME ": too many fields in Track record!\n");
+ gbWarning("too many fields in Track record!\n");
break;
}
const auto& [name, field_no] = header_mapping_info[track_header].at(column);
for (const auto& str : lineparts) {
if (++column >= header_mapping_info[rtept_header].size()) {
- warning(MYNAME ": too many fields in Route Waypoint record!\n");
+ gbWarning("too many fields in Route Waypoint record!\n");
break;
}
const auto& [name, field_no] = header_mapping_info[rtept_header].at(column);
switch (field_no) {
case 1:
if (str.isEmpty()) {
- fatal(MYNAME ": Route waypoint without name at line %d!\n", current_line);
+ gbFatal("Route waypoint without name at line %d!\n", current_line);
}
wpt = find_waypt_by_name(str);
if (wpt == nullptr) {
- fatal(FatalMsg() << MYNAME << ": Route waypoint " << str << " not in waypoint list (line " << current_line<< ")!\n");
+ gbFatal(FatalMsg() << "Route waypoint " << str << " not in waypoint list (line " << current_line<< ")!\n");
}
wpt = new Waypoint(*wpt);
break;
for (const auto& str : lineparts) {
if (++column >= header_mapping_info[trkpt_header].size()) {
- warning(MYNAME ": too many fields in Trackpoint record!\n");
+ gbWarning("too many fields in Trackpoint record!\n");
break;
}
double x;
switch (field_no) {
case 1:
parse_coordinates(str, datum_index, grid_index,
- &wpt->latitude, &wpt->longitude, MYNAME);
+ &wpt->latitude, &wpt->longitude);
break;
case 2:
if (QDateTime dt = parse_date_and_time(str); dt.isValid()) {
}
break;
case 3:
- if (parse_distance(str, &x, 1, MYNAME)) {
+ if (parse_distance(str, &x, 1)) {
wpt->altitude = x;
}
break;
case 4:
- if (parse_distance(str, &x, 1, MYNAME)) {
+ if (parse_distance(str, &x, 1)) {
wpt->set_depth(x);
}
break;
}
break;
case 8:
- if (parse_speed(str, &x, 1, MYNAME)) {
+ if (parse_speed(str, &x, 1)) {
wpt->set_speed(x);
}
break;
gtxt_flags = {};
fin = new gpsbabel::TextStream;
- fin->open(fname, QIODevice::ReadOnly, MYNAME, "windows-1252");
+ fin->open(fname, QIODevice::ReadOnly, "windows-1252");
free_headers();
header_column_names.clear();
parse_track_header(lineparts);
} else if (linetype.compare(u"Map", Qt::CaseInsensitive) == 0) /* do nothing */ ;
else {
- fatal(MYNAME ": Unknown identifier (%s) at line %d!\n", qPrintable(linetype), current_line);
+ gbFatal("Unknown identifier (%s) at line %d!\n", gbLogCStr(linetype), current_line);
}
}
#include "gbfile.h" // for gbfread, gbfgetuint16, gbfseek, gbfgetc, gbfgetuint32, gbfclose, gbfeof, gbfopen
-#define MYNAME "Garmin_XT"
#define GARMIN_XT_ELE 31500/65536
#define DATABLOCKSIZE 1
#define STRK_BLOCK_SIZE 97
void
GarminXTFormat::rd_init(const QString& fname)
{
- fin = gbfopen(fname, "rb", MYNAME);
+ fin = gbfopen(fname, "rb");
}
void
# define SET_BINARY_MODE(file)
#endif
-#define MYNAME "gbfile"
-#define NO_ZLIB MYNAME ": No zlib support.\n"
+#define NO_ZLIB "No zlib support.\n"
/* About the ZLIB_INHIBITED stuff:
*
}
if (self->handle.gz == nullptr) {
- fatal("%s: Cannot %s file '%s'!\n",
- qPrintable(self->module),
+ gbFatal("Cannot %s file '%s'!\n",
(self->mode == 'r') ? "open" : "create",
- qPrintable(self->name));
+ gbLogCStr(self->name));
}
return self;
if (result < 0) {
if (self->is_pipe) {
- fatal("%s: This format cannot be used in piped commands!\n", qPrintable(self->module));
+ gbFatal("This format cannot be used in piped commands!\n");
}
- fatal("%s: online compression not yet supported for this format!", qPrintable(self->module));
+ gbFatal("online compression not yet supported for this format!\n");
}
return 0;
}
/* Check for an incomplete READ */
if ((members == 1) && (size > 1) && (result > 0) && (result < (int)size)) {
- fatal("%s: Unexpected end of file (EOF)!\n", qPrintable(self->module));
+ gbFatal("Unexpected end of file (EOF)!\n");
}
result /= size;
return (gbsize_t) 0;
}
if ((errnum != Z_STREAM_END) && (errnum != 0))
- fatal("%s: zlib returned error %d ('%s')!\n",
- qPrintable(self->module), errnum, errtxt);
+ gbFatal("zlib returned error %d ('%s')!\n",
+ errnum, errtxt);
}
return (gbsize_t) result;
}
if (global_opts.debug_level > 0) {
/* now gzeof() should return 1 */
if (!gzeof(self->handle.gz)) {
- fatal("zlib gzeof error!\n");
+ gbFatal("zlib gzeof error!\n");
}
}
res = 1;
if (self->back == -1) {
self->back = c;
} else {
- fatal(MYNAME ": Cannot store more than one byte back!\n");
+ gbFatal("Cannot store more than one byte back!\n");
}
return c;
}
static gbfile*
stdapi_open(gbfile* self, const char* mode)
{
- self->handle.std = xfopen(self->name, mode, self->module);
+ self->handle.std = xfopen(self->name, mode);
return self;
}
pos = offset;
break;
default:
- fatal("%s: Unknown seek operation (%d) for file %s!\n",
- qPrintable(self->module), whence, qPrintable(self->name));
+ gbFatal("Unknown seek operation (%d) for file %s!\n",
+ whence, gbLogCStr(self->name));
}
- fatal("%s: Unable to set file (%s) to position (%llu)!\n",
- qPrintable(self->module), qPrintable(self->name), (long long unsigned) pos);
+ gbFatal("Unable to set file (%s) to position (%llu)!\n",
+ gbLogCStr(self->name), (long long unsigned) pos);
}
return 0;
}
gbsize_t result = fread(buf, size, members, self->handle.std);
if ((result < members) && (error_number = ferror(self->handle.std))) {
- fatal("%s: Error %d occurred during read of file '%s'!\n",
- qPrintable(self->module), error_number, qPrintable(self->name));
+ gbFatal("Error %d occurred during read of file '%s'!\n",
+ error_number, gbLogCStr(self->name));
}
return result;
}
/* GPSBabel 'file' standard calls */
/*
- * gbfopen: (as xfopen) plus the name of the calling GPSBabel module (MYNAME)
+ * gbfopen: (as xfopen)
*/
gbfile*
-gbfopen(const QString& filename, const char* mode, const QString& module)
+gbfopen(const QString& filename, const char* mode)
{
auto* file = new gbfile;
- file->module = module;
file->mode = 'r'; // default
file->binary = (strchr(mode, 'b') != nullptr);
file->back = -1;
/* force gzipped files on output */
file->gzapi = 1;
#else
- fatal(NO_ZLIB);
+ gbFatal(NO_ZLIB);
#endif
}
file->filewrite = gzapi_write;
#else
/* This is the only runtime test we make */
- fatal("%s: Zlib was not included in this build.\n", qPrintable(file->module));
+ gbFatal("Zlib was not included in this build.\n");
#endif
} else {
file->fileclearerr = stdapi_clearerr;
*/
gbfile*
-gbfopen_be(const QString& filename, const char* mode, const QString& module)
+gbfopen_be(const QString& filename, const char* mode)
{
- gbfile* result = gbfopen(filename, mode, module);
+ gbfile* result = gbfopen(filename, mode);
result->big_endian = 1;
return result;
gbsize_t nbytes = gbfread(tmp.data(), 1, size, file);
if (nbytes != size) {
- fatal(FatalMsg() << file->module << "Attempted to read " << size <<
+ gbFatal(FatalMsg() << "Attempted to read " << size <<
"bytes, but only " << nbytes << "were available.");
}
return tmp;
{
unsigned int result = file->filewrite(buf, size, members, file);
if (result != members) {
- fatal("%s: Could not write %lld bytes to %s (result %d)!\n",
- qPrintable(file->module),
+ gbFatal("Could not write %lld bytes to %s (result %d)!\n",
(long long int)(members - result) * size,
- qPrintable(file->name),
+ gbLogCStr(file->name),
result);
}
{
gbsize_t result = file->filetell(file);
if ((signed) result == -1)
- fatal("%s: Could not determine position of file '%s'!\n",
- qPrintable(file->module), qPrintable(file->name));
+ gbFatal("Could not determine position of file '%s'!\n",
+ gbLogCStr(file->name));
return result;
}
char buf[4];
if (gbfread(&buf, 1, sizeof(buf), file) != sizeof(buf)) {
- fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name));
+ gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name));
}
if (file->big_endian) {
char buf[2];
if (gbfread(&buf, 1, sizeof(buf), file) != sizeof(buf)) {
- fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name));
+ gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name));
}
if (file->big_endian) {
char buf[8];
if (gbfread(&buf, 1, sizeof(buf), file) != sizeof(buf)) {
- fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name));
+ gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name));
}
return endian_read_double(buf, ! file->big_endian);
char buf[4];
if (gbfread(&buf, 1, sizeof(buf), file) != sizeof(buf)) {
- fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name));
+ gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name));
}
return endian_read_float(buf, ! file->big_endian);
}
if (c == EOF) {
- fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name));
+ gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name));
}
if (len == file->buffsz) {
{
int len = gbfgetc(file);
if (len == EOF) {
- fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name));
+ gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name));
}
QByteArray ba;
ba.resize(len);
if (gbfread(ba.data(), 1, len, file) != (gbsize_t) len) {
- fatal("%s: Unexpected end of file (%s)!\n", qPrintable(file->module), qPrintable(file->name));
+ gbFatal("Unexpected end of file (%s)!\n", gbLogCStr(file->name));
}
return QString(ba);
int c1 = gbfgetc(file);
if (c1 == EOF) {
- fatal("%s: Incomplete unicode (UTF-16%cE) character at EOF!\n",
- qPrintable(file->module),
+ gbFatal("Incomplete unicode (UTF-16%cE) character at EOF!\n",
file->big_endian ? 'B' : 'L');
}
QChar qch2 = gbfgetutf16char(file);
if (qch2 != u'\n') { // including qch2.isNull()
// Putting back two chars may not be supported, e.g. with gzapi_ungetc.
- fatal("%s: Invalid unicode (UTF-16%cE) line break!\n",
- qPrintable(file->module),
+ gbFatal("Invalid unicode (UTF-16%cE) line break!\n",
file->big_endian ? 'B' : 'L');
}
break;
}
if (qch.isLowSurrogate()) {
- fatal("%s: Leading unicode (UTF-16%cE) low surrogate!\n",
- qPrintable(file->module),
+ gbFatal("Leading unicode (UTF-16%cE) low surrogate!\n",
file->big_endian ? 'B' : 'L');
}
if (qch.isHighSurrogate()) {
QChar qch2 = gbfgetutf16char(file);
if (!qch2.isLowSurrogate()) { // including qch2.isNull()
- fatal("%s: Missing unicode (UTF-16%cE) low surrogate!\n",
- qPrintable(file->module),
+ gbFatal("Missing unicode (UTF-16%cE) low surrogate!\n",
file->big_endian ? 'B' : 'L');
}
str.append(qch2);
#endif
} handle{nullptr};
QString name;
- QString module;
char* buff{nullptr}; /* static growing buffer, primary used by gbprintf */
int buffsz{0};
char mode{0};
};
-gbfile* gbfopen(const QString& filename, const char* mode, const QString& module);
-gbfile* gbfopen_be(const QString& filename, const char* mode, const QString& module);
-inline gbfile* gbfopen_le(const QString& filename, const char* mode, const QString& module)
+gbfile* gbfopen(const QString& filename, const char* mode);
+gbfile* gbfopen_be(const QString& filename, const char* mode);
+inline gbfile* gbfopen_le(const QString& filename, const char* mode)
{
- return gbfopen(filename, mode, module);
+ return gbfopen(filename, mode);
}
void gbfclose(gbfile* file);
void gbser_db(int l, const char* msg, ...)
{
- va_list ap;
- va_start(ap, msg);
if (global_opts.debug_level >= l) {
+ va_list ap;
+ va_start(ap, msg);
vprintf(msg, ap);
+ va_end(ap);
}
- va_end(ap);
}
/* Set the serial port speed.
return B230400;
#endif
default:
- fatal("Unsupported serial speed: %d\n", br);
+ gbFatal("Unsupported serial speed: %d\n", br);
return 0; /* keep compiler happy */
}
}
h->fd = 0;
return h;
} else if (h->fd = open(port_name, O_RDWR | O_NOCTTY), h->fd == -1) {
- warning("Failed to open port (%s)\n", strerror(errno));
+ gbWarning("Failed to open port (%s)\n", strerror(errno));
goto failed;
}
if (!isatty(h->fd)) {
- warning("%s is not a TTY\n", port_name);
+ gbWarning("%s is not a TTY\n", port_name);
goto failed;
}
if (gbser_set_port(h, 4800, 8, 0, 1)) {
- warning("gbser_set_port() failed\n");
+ gbWarning("gbser_set_port() failed\n");
goto failed;
}
};
if (bits < 5 || bits > 8) {
- fatal("Unsupported bits setting: %d\n", bits);
+ gbFatal("Unsupported bits setting: %d\n", bits);
}
if (parity > 2) {
- fatal("Unsupported parity setting: %d\n", parity);
+ gbFatal("Unsupported parity setting: %d\n", parity);
}
if (stop < 1 || stop > 2) {
- fatal("Unsupported stop setting: %d\n", stop);
+ gbFatal("Unsupported stop setting: %d\n", stop);
}
s = mkspeed(speed);
return 230400;
#endif
default:
- fatal("Unsupported serial speed: %d\n", br);
+ gbFatal("Unsupported serial speed: %d\n", br);
return 0; /* keep compiler happy */
}
}
DCB tio;
if (bits < 5 || bits > 8) {
- fatal("Unsupported bits setting: %d\n", bits);
+ gbFatal("Unsupported bits setting: %d\n", bits);
}
if (parity > 2) {
- fatal("Unsupported parity setting: %d\n", parity);
+ gbFatal("Unsupported parity setting: %d\n", parity);
}
if (stop < 1 || stop > 2) {
- fatal("Unsupported stop setting: %d\n", stop);
+ gbFatal("Unsupported stop setting: %d\n", stop);
}
tio.DCBlength = sizeof(DCB);
#include <QtGlobal> // for Q_UNUSED, qPrintable, foreach
#include <cmath> // for fabs
-#include <cstdio> // for printf, SEEK_SET
+#include <cstdio> // for SEEK_SET
#include <cstring> // for memset, strstr, strcmp
#include <iterator> // for next
-#include "defs.h" // for Waypoint, warning, route_head, fatal, UrlLink, bounds, UrlList, unknown_alt, xfree, waypt_add_to_bounds, waypt_init_bounds, route_add_wpt, route_disp_all, waypt_bounds_valid, xmalloc, gb_color, WaypointList, find_wa...
+#include "defs.h" // for Waypoint, gbWarning, route_head, gbFatal, UrlLink, bounds, UrlList, unknown_alt, xfree, waypt_add_to_bounds, waypt_init_bounds, route_add_wpt, route_disp_all, waypt_bounds_valid, xmalloc, gb_color, WaypointList, find_wa...
#include "formspec.h" // for FormatSpecificDataList
#include "garmin_fs.h" // for garmin_fs_t, garmin_ilink_t
#include "garmin_tables.h" // for gt_waypt_class_map_point, gt_color_index_by_rgb, gt_color_value, gt_waypt_classes_e, gt_find_desc_from_icon_number, gt_find_icon_number_from_desc, gt_gdb_display_mode_symbol, gt_get_icao_country, gt_waypt_class_user_waypoint, GDB, gt_display_mode_symbol
#include "src/core/datetime.h" // for DateTime
-#define MYNAME "gdb"
-
#define GDB_DEF_CLASS gt_waypt_class_user_waypoint
#define GDB_DEF_HIDDEN_CLASS gt_waypt_class_map_point
GdbFormat::disp_summary(const gbfile* f) const
{
if constexpr(GDB_DEBUG) {
- int len = strlen(qPrintable(f->name));
+ int len = strlen(gbLogCStr(f->name));
- warning(MYNAME ": =====================");
- for (int i = 0; i < len; i++) {
- warning("=");
- }
- warning("\n" MYNAME ": %s summary for \"%s\"\n",
- (f->mode == 'r') ? "Reader" : "Writer", qPrintable(f->name));
+ gbWarning("%s\n", QByteArray(len + 21, '=').constData());
- warning(MYNAME ": ---------------------");
- for (int i = 0; i < len; i++) {
- warning("-");
- }
+ gbWarning("%s summary for \"%s\"\n",
+ (f->mode == 'r') ? "Reader" : "Writer", gbLogCStr(f->name));
- warning("\n" MYNAME ": %d waypoint(s)\n", waypt_ct - waypth_ct);
- warning(MYNAME ": %d hidden waypoint(s)\n", waypth_ct);
- warning(MYNAME ": %d route(s) with total %d point(s)\n", rte_ct, rtept_ct);
- warning(MYNAME ": %d track(s) with total %d point(s)\n", trk_ct, trkpt_ct);
- warning(MYNAME ": ---------------------");
+ gbWarning("%s\n", QByteArray(len + 21, '-').constData());
- for (int i = 0; i < len; i++) {
- warning("-");
- }
- warning("\n");
+ gbWarning("%d waypoint(s)\n", waypt_ct - waypth_ct);
+ gbWarning("%d hidden waypoint(s)\n", waypth_ct);
+ gbWarning("%d route(s) with total %d point(s)\n", rte_ct, rtept_ct);
+ gbWarning("%d track(s) with total %d point(s)\n", trk_ct, trkpt_ct);
+
+ gbWarning("%s\n", QByteArray(len + 21, '-').constData());
} else {
Q_UNUSED(f);
}
double dist = radtometers(gcdist(ref->position(), tmp->position()));
if (fabs(dist) > 100) {
- fatal(MYNAME ": Route point mismatch!\n" \
+ gbFatal("Route point mismatch!\n" \
" \"%s\" from waypoints differs to \"%s\"\n" \
" from route table by more than %0.1f meters!\n", \
- qPrintable(tmp->shortname), qPrintable(ref->shortname), dist);
+ gbLogCStr(tmp->shortname), gbLogCStr(ref->shortname), dist);
}
}
Waypoint* res = nullptr;
misinterpreted.
*/
if (strcmp(buf, "MsRcf") != 0) {
- fatal(MYNAME ": Invalid file \"%s\"!", qPrintable(fin->name));
+ gbFatal("Invalid file \"%s\"!\n", gbLogCStr(fin->name));
}
int reclen = FREAD_i32;
Q_UNUSED(reclen);
QByteArray drec = FREAD_STR();
if (drec.at(0) != 'D') {
- fatal(MYNAME ": Invalid file \"%s\"!", qPrintable(fin->name));
+ gbFatal("Invalid file \"%s\"!\n", gbLogCStr(fin->name));
}
gdb_ver = drec.at(1) - 'k' + 1;
if ((gdb_ver < kGDBVerMin) || (gdb_ver > kGDBVerMax)) {
- fatal(MYNAME ": Unknown or/and unsupported GDB version (%d.0)!", gdb_ver);
+ gbFatal("Unknown or/and unsupported GDB version (%d.0)!\n", gdb_ver);
}
if (global_opts.verbose_status > 0) {
- printf(MYNAME ": Reading Garmin GPS Database version %d.0\n", gdb_ver);
+ gbInfo("Reading Garmin GPS Database version %d.0\n", gdb_ver);
}
reclen = FREAD_i32;
if (reclen + 1 > int(sizeof(buf))) {
- fatal(MYNAME ": Invalid record length\n");
+ gbFatal("Invalid record length\n");
}
(void) FREAD(buf, reclen + 1);
if (global_opts.verbose_status > 0) {
} else if (strstr(name, "neaderhi") == nullptr) {
name = "MapSource BETA";
}
- warning(MYNAME ": File created with \"%s\"\n", name);
+ gbWarning("File created with \"%s\"\n", name);
}
QByteArray applicationField = FREAD_STR();
if (!((applicationField == "MapSource") || (applicationField == "BaseCamp"))) {
- fatal(MYNAME ": Not a recognized signature in header");
+ gbFatal("Not a recognized signature in header\n");
}
}
res->altitude = alt;
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, true)
- printf(MYNAME "-wpt \"%s\" (%d): Altitude = %.1f\n",
- qPrintable(res->shortname), wpt_class, alt);
+ gbDebug("wpt \"%s\" (%d): Altitude = %.1f\n",
+ gbLogCStr(res->shortname), wpt_class, alt);
}
}
}
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPT, true)
- printf(MYNAME "-wpt \"%s\": coordinates = %c%0.6f %c%0.6f\n",
- qPrintable(res->shortname),
+ gbDebug("wpt \"%s\": coordinates = %c%0.6f %c%0.6f\n",
+ gbLogCStr(res->shortname),
res->latitude < 0 ? 'S' : 'N', res->latitude,
res->longitude < 0 ? 'W' : 'E', res->longitude);
}
res->notes = fread_cstr();
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, !res->notes.isNull())
- printf(MYNAME "-wpt \"%s\" (%d): notes = %s\n",
- qPrintable(res->shortname), wpt_class,
- qPrintable(QString(res->notes).replace("\r\n", ", ")));
+ gbDebug("wpt \"%s\" (%d): notes = %s\n",
+ gbLogCStr(res->shortname), wpt_class,
+ gbLogCStr(QString(res->notes).replace("\r\n", ", ")));
}
if (FREAD_C == 1) {
res->set_proximity(FREAD_DBL);
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, res->proximity_has_value())
- printf(MYNAME "-wpt \"%s\" (%d): Proximity = %.1f\n",
- qPrintable(res->shortname), wpt_class, res->proximity_value() / 1000);
+ gbDebug("wpt \"%s\" (%d): Proximity = %.1f\n",
+ gbLogCStr(res->shortname), wpt_class, res->proximity_value() / 1000);
}
}
int display = FREAD_i32;
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, true)
- printf(MYNAME "-wpt \"%s\" (%d): display = %d\n",
- qPrintable(res->shortname), wpt_class, display);
+ gbDebug("wpt \"%s\" (%d): display = %d\n",
+ gbLogCStr(res->shortname), wpt_class, display);
}
switch (display) { /* display value */
case gt_gdb_display_mode_symbol:
res->set_depth(FREAD_DBL);
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, res->depth_has_value())
- printf(MYNAME "-wpt \"%s\" (%d): Depth = %.1f\n",
- qPrintable(res->shortname), wpt_class, res->depth_value());
+ gbDebug("wpt \"%s\" (%d): Depth = %.1f\n",
+ gbLogCStr(res->shortname), wpt_class, res->depth_value());
}
}
if constexpr(GDB_DEBUG) {
QString temp = FREAD_CSTR_AS_QSTR; /* undocumented & unused string */
DBG(GDB_DBG_WPTe, !temp.isEmpty())
- printf(MYNAME "-wpt \"%s\" (%d): Unknown string = %s\n",
- qPrintable(res->shortname), wpt_class, qPrintable(temp));
+ gbDebug("wpt \"%s\" (%d): Unknown string = %s\n",
+ gbLogCStr(res->shortname), wpt_class, gbLogCStr(temp));
} else {
(void) FREAD_CSTR_AS_QSTR; /* undocumented & unused string */
}
res->notes = QStringLiteral("[%1]").arg(gdb_to_ISO8601_duration(duration));
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, true)
- printf(MYNAME "-wpt \"%s\" (%d): duration = %u\n",
- qPrintable(res->shortname), wpt_class, duration);
+ gbDebug("wpt \"%s\" (%d): duration = %u\n",
+ gbLogCStr(res->shortname), wpt_class, duration);
}
}
int url_ct = FREAD_i32;
waypt_add_url(res, str, nullptr);
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, true)
- printf(MYNAME "-wpt \"%s\" (%d): url(%d) = %s\n",
- qPrintable(res->shortname), wpt_class, url_ct - i, qPrintable(str));
+ gbDebug("wpt \"%s\" (%d): url(%d) = %s\n",
+ gbLogCStr(res->shortname), wpt_class, url_ct - i, gbLogCStr(str));
}
}
}
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, !res->description.isNull())
- printf(MYNAME "-wpt \"%s\" (%d): description = %s\n",
- qPrintable(res->shortname), wpt_class, qPrintable(res->description));
+ gbDebug("wpt \"%s\" (%d): description = %s\n",
+ gbLogCStr(res->shortname), wpt_class, gbLogCStr(res->description));
DBG(GDB_DBG_WPTe, res->urls.HasUrlLink())
- printf(MYNAME "-wpt \"%s\" (%d): url = %s\n",
- qPrintable(res->shortname), wpt_class, qPrintable(res->urls.GetUrlLink().url_));
+ gbDebug("wpt \"%s\" (%d): url = %s\n",
+ gbLogCStr(res->shortname), wpt_class, gbLogCStr(res->urls.GetUrlLink().url_));
}
int category = FREAD_i16;
if (category != 0) {
}
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, category)
- printf(MYNAME "-wpt \"%s\" (%d): category = %d\n",
- qPrintable(res->shortname), wpt_class, category);
+ gbDebug("wpt \"%s\" (%d): category = %d\n",
+ gbLogCStr(res->shortname), wpt_class, category);
}
if (FREAD_C == 1) {
res->set_temperature(FREAD_DBL);
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, res->temperature_has_value())
- printf(MYNAME "-wpt \"%s\" (%d): temperature = %.1f\n",
- qPrintable(res->shortname), wpt_class, res->temperature_value());
+ gbDebug("wpt \"%s\" (%d): temperature = %.1f\n",
+ gbLogCStr(res->shortname), wpt_class, res->temperature_value());
}
}
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_WPTe, icon != kGDBDefIcon)
- printf(MYNAME "-wpt \"%s\" (%d): icon = \"%s\" (MapSource symbol %d)\n",
- qPrintable(res->shortname), wpt_class, qPrintable(res->icon_descr), icon);
+ gbDebug("wpt \"%s\" (%d): icon = \"%s\" (MapSource symbol %d)\n",
+ gbLogCStr(res->shortname), wpt_class, gbLogCStr(res->icon_descr), icon);
}
QString str;
if (!(str = garmin_fs_t::get_cc(gmsd, nullptr)).isEmpty()) {
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_RTE, true)
- printf(MYNAME "-rte \"%s\": loading route with %d point(s)...\n",
- qPrintable(rte->rte_name), points);
+ gbDebug("rte \"%s\": loading route with %d point(s)...\n",
+ gbLogCStr(rte->rte_name), points);
}
for (int i = 0; i < points; i++) {
if ((buf[0] != 0x00) && (buf[0] != 0x01) && (buf[0] != 0x03)) {
warnings++;
if (warnings > 3) {
- fatal(MYNAME "-rte_pt \"%s\": too many warnings!\n", qPrintable(wpt->shortname));
+ gbFatal("rte_pt \"%s\": too many warnings!\n", gbLogCStr(wpt->shortname));
}
- warning(MYNAME "-rte_pt \"%s\" (class %d): possible error in route.\n", qPrintable(wpt->shortname), wpt_class);
- warning(MYNAME "-rte_pt (dump):");
+ gbWarning("rte_pt \"%s\" (class %d): possible error in route.\n", gbLogCStr(wpt->shortname), wpt_class);
+ gbWarning("rte_pt (dump):");
for (int idx = 0; idx < 18; idx++) {
- warning(" %02x", (unsigned char)buf[idx]);
+ gbWarning(" %02x", (unsigned char)buf[idx]);
}
- warning("\n");
+ gbWarning("\n");
}
int links = FREAD_i32;
QList<garmin_ilink_t> il_list;
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_RTE, links)
- printf(MYNAME "-rte_pt \"%s\" (%d): %d interlink step(s)\n",
- qPrintable(wpt->shortname), wpt_class, links);
+ gbDebug("rte_pt \"%s\" (%d): %d interlink step(s)\n",
+ gbLogCStr(wpt->shortname), wpt_class, links);
}
for (int j = 0; j < links; j++) {
garmin_ilink_t il_step;
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_RTEe, true) {
- printf(MYNAME "-rte_il \"%s\" (%d of %d): %c%0.6f %c%0.6f\n",
- qPrintable(wpt->shortname), j + 1, links,
+ gbDebug("rte_il \"%s\" (%d of %d): %c%0.6f %c%0.6f\n",
+ gbLogCStr(wpt->shortname), j + 1, links,
il_step.lat < 0 ? 'S' : 'N', il_step.lat,
il_step.lon < 0 ? 'W' : 'E', il_step.lon);
}
wpt = new Waypoint(*tmp);
} else {
if (waypt_bounds_valid(&bounds)) {
- warning(MYNAME ": (has bounds)\n");
+ gbWarning("(has bounds)\n");
}
- warning(MYNAME ": Data corruption detected!\n");
- fatal(MYNAME ": Sleeping route point without coordinates!\n");
+ gbWarning("Data corruption detected!\n");
+ gbFatal("Sleeping route point without coordinates!\n");
}
}
}
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_RTE, true)
- printf(MYNAME "-rte_pt \"%s\": coordinates = %c%0.6f, %c%0.6f\n",
- qPrintable(wpt->shortname),
+ gbDebug("rte_pt \"%s\": coordinates = %c%0.6f, %c%0.6f\n",
+ gbLogCStr(wpt->shortname),
wpt->latitude < 0 ? 'S' : 'N', wpt->latitude,
wpt->longitude < 0 ? 'W' : 'E', wpt->longitude);
}
FREAD(tbuf, 8); /* unknown bytes */
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_RTE, true)
- printf(MYNAME "-rte_pt: autoroute info: route style %d, calculation type %d, vehicle type %d, road selection %d\n"
+ gbDebug("rte_pt: autoroute info: route style %d, calculation type %d, vehicle type %d, road selection %d\n"
" driving speeds (kph) %.0f, %.0f, %.0f, %.0f, %.0f\n",
route_style, calc_type, vehicle_type, road_selection,
driving_speed[0], driving_speed[1], driving_speed[2], driving_speed[3], driving_speed[4]);
}
if constexpr(GDB_DEBUG) {
DBG(GDB_DBG_TRK, res->rte_urls.HasUrlLink())
- printf(MYNAME "-trk \"%s\": url = %s\n",
- qPrintable(res->rte_name), qPrintable(res->rte_urls.GetUrlLink().url_));
+ gbDebug("trk \"%s\": url = %s\n",
+ gbLogCStr(res->rte_name), gbLogCStr(res->rte_urls.GetUrlLink().url_));
}
return res;
}
void
GdbFormat::rd_init(const QString& fname)
{
- fin = gbfopen_le(fname, "rb", MYNAME);
- ftmp = gbfopen_le(nullptr, "wb", MYNAME);
+ fin = gbfopen_le(fname, "rb");
+ ftmp = gbfopen_le(nullptr, "wb");
read_file_header();
waypt_nameposn_in_hash.clear();
int len = FREAD_i32;
if (FREAD(&typ, 1) < 1) {
- fatal(MYNAME ": Attempt to read past EOF.");
+ gbFatal("Attempt to read past EOF.\n");
}
if (typ == 'V') {
break; /* break the loop */
int delta = len - gbftell(ftmp);
if (delta > 1000000) {
- fatal("Internal consistency error. Delta too big");
+ gbFatal("Internal consistency error. Delta too big\n");
}
// Avoid finite loop on bogus beta files from '06.
if (dump && delta) {
if (! incomplete++) {
- warning(MYNAME ":==========================================\n");
- warning(MYNAME ":=== W A R N I N G ===\n");
+ gbWarning("==========================================\n");
+ gbWarning("=== W A R N I N G ===\n");
}
if (typ == 'W')
- warning(MYNAME ":(%d%c-%02d): delta = %d (flag=%3d/%02x)-",
+ gbWarning("(%d%c-%02d): delta = %d (flag=%3d/%02x)-",
gdb_ver, typ, wpt_class, delta, waypt_flag, waypt_flag);
else {
- warning(MYNAME ":(%d%c): delta = %d -", gdb_ver, typ, delta);
+ gbWarning("(%d%c): delta = %d -", gdb_ver, typ, delta);
}
if (delta > 0) {
char* buf = (char*) xmalloc(delta);
if (FREAD(buf, delta) < 1) {
- fatal(MYNAME ": Attempt to read past EOF.\n");
+ gbFatal("Attempt to read past EOF.\n");
}
for (int i = 0; i < delta; i++) {
- warning(" %02x", (unsigned char)buf[i]);
+ gbWarning(" %02x", (unsigned char)buf[i]);
}
xfree(buf);
}
- warning("\n");
+ gbWarning("\n");
}
fin = fsave;
if (incomplete) {
- warning(MYNAME ":------------------------------------------\n");
- warning(MYNAME ": \"%s\"\n", qPrintable(fin->name));
- warning(MYNAME ":------------------------------------------\n");
- warning(MYNAME ": Please mail this information\n");
- warning(MYNAME " and, if you can, the used GDB file\n");
- warning(MYNAME ": to gpsbabel-misc@lists.sourceforge.net\n");
- warning(MYNAME ":==========================================\n");
+ gbWarning("------------------------------------------\n");
+ gbWarning("\"%s\"\n", gbLogCStr(fin->name));
+ gbWarning("------------------------------------------\n");
+ gbWarning("Please mail this information\n");
+ gbWarning("and, if you can, the used GDB file\n");
+ gbWarning("to gpsbabel-misc@lists.sourceforge.net\n");
+ gbWarning("==========================================\n");
}
}
if (test != nullptr) {
wpt = test;
} else {
- fatal(MYNAME ": Sorry, that should never happen!!!\n");
+ gbFatal("Sorry, that should never happen!!!\n");
}
const garmin_fs_t* gmsd = garmin_fs_t::find(wpt);
void
GdbFormat::wr_init(const QString& fname)
{
- fout = gbfopen_le(fname, "wb", MYNAME);
- ftmp = gbfopen_le(nullptr, "wb", MYNAME);
+ fout = gbfopen_le(fname, "wb");
+ ftmp = gbfopen_le(nullptr, "wb");
gdb_category = gdb_opt_category ? gdb_opt_category.get_result() : 0;
gdb_ver = gdb_opt_ver.get_result();
if (gdb_category) {
if ((gdb_category < 1) || (gdb_category > 16)) {
- fatal(MYNAME ": cat must be between 1 and 16!");
+ gbFatal("cat must be between 1 and 16!\n");
}
gdb_category = 1 << (gdb_category - 1);
}
#include "src/core/file.h" // for File
-#define MYNAME "geo"
-
void GeoFormat::GeoReadLoc(QXmlStreamReader& reader)
{
Waypoint* wpt = nullptr;
GeoReadLoc(reader);
if (reader.hasError()) {
- fatal(MYNAME ":Read error: %s (%s, line %ld, col %ld)\n",
- qPrintable(reader.errorString()),
- qPrintable(ifile.fileName()),
+ gbFatal("Read error: %s (%s, line %ld, col %ld)\n",
+ gbLogCStr(reader.errorString()),
+ gbLogCStr(ifile.fileName()),
(long) reader.lineNumber(),
(long) reader.columnNumber());
}
QJsonParseError error{};
QJsonDocument document = QJsonDocument::fromJson(file_content.toUtf8(), &error);
if (error.error != QJsonParseError::NoError) {
- fatal(FatalMsg().nospace() << MYNAME << ": GeoJSON parse error in " << ifd->fileName() << ": " << error.errorString());
+ gbFatal(FatalMsg().nospace() << "GeoJSON parse error in " << ifd->fileName() << ": " << error.errorString());
}
QJsonObject rootObject = document.object();
gpsbabel::File* ifd{nullptr};
gpsbabel::File* ofd{nullptr};
- const char* MYNAME = "geojson";
OptionBool compact_opt;
QJsonObject* track_object = nullptr;
QJsonArray* track_coords = nullptr;
*/
#include <cstdint>
-#include <cstdio> // for printf
#include <cstdlib> // for free, malloc
#include <QByteArray> // for QByteArray
#include <QString> // for QString
#include <QTime> // for QTime
#include <QTimeZone> // for QTimeZone
-#include <Qt> // for LocalTime
#include <QtGlobal> // for qPrintable
#include "defs.h"
#include "src/core/datetime.h" // for DateTime
-#define MYNAME "GlobalsatSport"
-
void
GlobalsatSportFormat::serial_init(const char* fname)
{
if (serial_handle = gbser_init(fname), nullptr == serial_handle) {
- fatal(MYNAME ": Can't open port '%s'\n", fname);
+ gbFatal("Can't open port '%s'\n", fname);
}
if (gbser_set_speed(serial_handle, 115200) != gbser_OK) {
- fatal(MYNAME ": Can't configure port '%s'\n", fname);
+ gbFatal("Can't configure port '%s'\n", fname);
}
// Toss anything that came in before our speed was set
gbser_flush(serial_handle);
GlobalsatSportFormat::serial_deinit()
{
if (global_opts.debug_level > 1) {
- printf(MYNAME " serial_deinit()\n");
+ gbDebug("serial_deinit()\n");
}
gbser_deinit(serial_handle);
serial_handle = nullptr;
if (global_opts.debug_level > 1) {
- printf(MYNAME " serial_deinit() Done\n");
+ gbDebug("serial_deinit() Done\n");
}
}
int result = gbser_readc_wait(serial_handle, 4000);
switch (result) {
case gbser_ERROR:
- fatal("serial_recv_byte(): error reading one byte\n");
+ gbFatal("serial_recv_byte(): error reading one byte\n");
break;
case gbser_NOTHING:
- fatal("serial_recv_byte(): read timeout\n");
+ gbFatal("serial_recv_byte(): read timeout\n");
break;
}
return result;
}
void
-GlobalsatSportFormat::serial_write_byte(uint8_t byte) const
+GlobalsatSportFormat::serial_write_byte(uint8_t byte)
{
if (global_opts.debug_level > 1) {
- printf("0x%02x (%d), ", byte, byte);
+ gbDebug("0x%02x (%d), ", byte, byte);
}
int n = gbser_writec(serial_handle, byte);
if (n == gbser_ERROR) {
- fatal("globalsat_probe_device(): write failed\n");
+ gbFatal("globalsat_probe_device(): write failed\n");
}
}
} else {
result = gbfgetc(in_file);
if (result < 0) {
- fatal(MYNAME ": read error");
+ gbFatal("read error\n");
}
}
// Check if byte should be dumped also into a file
}
write_byte(crc);
if (global_opts.debug_level > 1) {
- printf("\n");
+ gbDebug("\n");
}
}
uint8_t DeviceCommand = recv_byte();
if (global_opts.debug_level > 1) {
- printf("DeviceCommand: 0x%02x ", DeviceCommand);
+ gbDebug("DeviceCommand: 0x%02x ", DeviceCommand);
}
uint8_t len_h = recv_byte();
calc_crc ^= len_h;
int length = (len_h << 8) + len_l;
if (global_opts.debug_level > 1) {
- printf("len=%d Payload:", length);
+ gbDebug("len=%d Payload:", length);
}
auto* payload = (uint8_t*) malloc(length);
crc = recv_byte();
if (global_opts.debug_level > 1) {
- printf("crc=0x%x should be=0x%x\n", crc, calc_crc);
+ gbDebug("crc=0x%x should be=0x%x\n", crc, calc_crc);
}
if (crc == calc_crc) {
*out_DeviceCommand = DeviceCommand;
uint8_t* payload = globalsat_read_package(&len, &DeviceCommand);
if ((len > 0) && (payload != nullptr)) {
if (global_opts.debug_level > 1) {
- printf("Got package!!!\n");
+ gbDebug("Got package!!!\n");
}
//TODO figure out what device it is if we start to support more devices then gh625XT
}
GlobalsatSportFormat::rd_init(const QString& fname)
{
if (global_opts.debug_level > 1) {
- printf(MYNAME " rd_init()\n");
+ gbDebug("rd_init()\n");
}
if (opt_dump_file) {
- dumpfile = gbfopen(opt_dump_file, "wb", MYNAME);
+ dumpfile = gbfopen(opt_dump_file, "wb");
if (!dumpfile) {
- printf(MYNAME " rd_init() creating dumpfile %s FAILED continue anyway\n", qPrintable(opt_dump_file));
+ gbWarning("rd_init() creating dumpfile %s FAILED continue anyway\n", gbLogCStr(opt_dump_file));
} else {
if (global_opts.debug_level > 1) {
- printf(MYNAME " rd_init() creating dumpfile %s for writing binary copy of serial stream\n", qPrintable(opt_dump_file));
+ gbDebug("rd_init() creating dumpfile %s for writing binary copy of serial stream\n", gbLogCStr(opt_dump_file));
}
}
}
serial_init(qPrintable(fname));
} else {
// read from dump-file instead of serial
- in_file = gbfopen(fname, "rb", MYNAME);
+ in_file = gbfopen(fname, "rb");
if (!in_file) {
- fatal("Could not open dumpfile for input: %s", qPrintable(fname));
+ gbFatal("Could not open dumpfile for input: %s\n", gbLogCStr(fname));
}
}
timezn = new QTimeZone(opt_timezone.get().toUtf8());
} else {
list_timezones();
- fatal(MYNAME ": Requested time zone \"%s\" not available.\n", qPrintable(opt_timezone));
+ gbFatal("Requested time zone \"%s\" not available.\n", gbLogCStr(opt_timezone));
}
} else {
timezn = nullptr;
GlobalsatSportFormat::rd_deinit()
{
if (global_opts.debug_level > 1) {
- printf(MYNAME " rd_deinit()\n");
+ gbDebug("rd_deinit()\n");
}
if (!opt_input_dump_file) {
serial_deinit();
timezn = nullptr;
}
if (global_opts.debug_level > 1) {
- printf(MYNAME " rd_deinit() Done\n");
+ gbDebug("rd_deinit() Done\n");
}
}
GlobalsatSportFormat::waypoint_read()
{
if (global_opts.debug_level > 1) {
- printf(MYNAME " waypoint_read()\n");
+ gbDebug(" waypoint_read()\n");
}
//CommandGetTrackFileHeaders
globalsat_send_simple(CommandGetWaypoints);
uint8_t* in_payload = globalsat_read_package(&len, &DeviceCommand);
if ((len > 0) && (in_payload != nullptr)) {
if (global_opts.debug_level > 1) {
- printf("Got package!!!\n");
+ gbDebug("Got package!!!\n");
}
}
if (in_payload) {
GlobalsatSportFormat::track_read()
{
if (global_opts.debug_level > 1) {
- printf(MYNAME " track_read()\n");
+ gbDebug(" track_read()\n");
}
//CommandGetTrackFileHeaders
globalsat_send_simple(CommandGetTrackFileHeaders);
if (global_opts.debug_level > 1) {
- printf("Sent...\n");
+ gbDebug("Sent...\n");
}
int length;
uint8_t* payload = globalsat_read_package(&length, &DeviceCommand);
if ((length > 0) && (payload != nullptr)) {
if (global_opts.debug_level > 1) {
- printf("Got package!!! headers\n");
+ gbDebug("Got package!!! headers\n");
}
//payload is packed with a number of trainingheaders with the size of 29bytes each
int number_headers = length / 29; //29=packed sizeof(gh_trainheader)
if (global_opts.debug_level > 1) {
- printf("length=%d sizeof(gh_trainheader)=%d number_headers=%d\n", length, 29, number_headers);
+ gbDebug("length=%d sizeof(gh_trainheader)=%d number_headers=%d\n", length, 29, number_headers);
}
for (int i = 0; i < number_headers; i++) {
th_header.DataType = th_hdr[28];
if (showlist || global_opts.debug_level > 1) {
- printf("Track[%02i]: %02d-%02d-%02d ", i, th_header.dateStart.Year, th_header.dateStart.Month, th_header.dateStart.Day);
- printf("%02d:%02d:%02d ", th_header.timeStart.Hour, th_header.timeStart.Minute, th_header.timeStart.Second);
+ gbDebug("Track[%02i]: %02d-%02d-%02d ", i, th_header.dateStart.Year, th_header.dateStart.Month, th_header.dateStart.Day);
+ gbDebug("%02d:%02d:%02d ", th_header.timeStart.Hour, th_header.timeStart.Minute, th_header.timeStart.Second);
int time_s=th_header.TotalTime / 10;
int time_h=time_s/(60*60);
time_s-=time_h*(60*60);
int time_m=time_s/60;
time_s-=time_m*60;
- printf("Points:%6u Time:%02d:%02d:%02d Dist:%9um LapCnts:%5d ", th_header.TotalPoint, time_h, time_m, time_s, th_header.TotalDistance, th_header.LapCnts);
- printf("Index/StartPt:%u ", th_header.gh_ptrec.Index);
- printf("LapIndex/EndPt:%u ", th_header.gh_laprec.LapIndex);
- printf("DataType:0x%x\n", th_header.DataType);
+ gbDebug("Points:%6u Time:%02d:%02d:%02d Dist:%9um LapCnts:%5d ", th_header.TotalPoint, time_h, time_m, time_s, th_header.TotalDistance, th_header.LapCnts);
+ gbDebug("Index/StartPt:%u ", th_header.gh_ptrec.Index);
+ gbDebug("LapIndex/EndPt:%u ", th_header.gh_laprec.LapIndex);
+ gbDebug("DataType:0x%x\n", th_header.DataType);
}
if (!showlist) {
int track_length;
uint8_t* track_payload = globalsat_read_package(&track_length, &trackDeviceCommand);
if ((track_length == 0) || (track_payload == nullptr)) {
- fatal(MYNAME ": track length is 0 bytes or payload nonexistent.\n");
+ gbFatal("track length is 0 bytes or payload nonexistent.\n");
}
// printf("Got track package!!! Train data\n");
db_train.Sport5 = dbtrain[57];
if (global_opts.debug_level > 1) {
- printf("\nTrainData:%02d-%02d-%02d ", db_train.dateStart.Year, db_train.dateStart.Month, db_train.dateStart.Day);
- printf("%02d:%02d:%02d ", db_train.timeStart.Hour, db_train.timeStart.Minute, db_train.timeStart.Second);
- printf("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", db_train.TotalPoint, db_train.TotalTime / 10, db_train.TotalDistance, db_train.LapCnts);
- printf("Index/StartPt:%u ", db_train.gh_ptrec.Index);
- printf("LapIndex/EndPt:%u ", db_train.gh_laprec.LapIndex);
- printf("MultiSport:0x%x ", db_train.MultiSport);
+ gbDebug("\nTrainData:%02d-%02d-%02d ", db_train.dateStart.Year, db_train.dateStart.Month, db_train.dateStart.Day);
+ gbDebug("%02d:%02d:%02d ", db_train.timeStart.Hour, db_train.timeStart.Minute, db_train.timeStart.Second);
+ gbDebug("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", db_train.TotalPoint, db_train.TotalTime / 10, db_train.TotalDistance, db_train.LapCnts);
+ gbDebug("Index/StartPt:%u ", db_train.gh_ptrec.Index);
+ gbDebug("LapIndex/EndPt:%u ", db_train.gh_laprec.LapIndex);
+ gbDebug("MultiSport:0x%x ", db_train.MultiSport);
}
int total_laps = db_train.LapCnts;
int total_laps_left = total_laps;
globalsat_send_simple(CommandGetNextTrackSection);
track_payload = globalsat_read_package(&track_length, &trackDeviceCommand);
if ((track_length == 0) || (track_payload == nullptr)) {
- fatal(MYNAME ": track length is 0 bytes or payload nonexistent.\n");
+ gbFatal("track length is 0 bytes or payload nonexistent.\n");
}
// printf("Got track package!!! Laps data\n");
if (global_opts.debug_level > 1) {
- printf("Lap Trainheader: %02d-%02d-%02d ", header.dateStart.Year, header.dateStart.Month, header.dateStart.Day);
- printf("%02d:%02d:%02d ", header.timeStart.Hour, header.timeStart.Minute, header.timeStart.Second);
- printf("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", header.TotalPoint, header.TotalTime / 10, header.TotalDistance, header.LapCnts);
- printf("Index/StartPt:%u ", header.gh_ptrec.Index);
- printf("LapIndex/EndPt:%u ", header.gh_laprec.LapIndex);
- printf("DataType:0x%x\n", header.DataType);
+ gbDebug("Lap Trainheader: %02d-%02d-%02d ", header.dateStart.Year, header.dateStart.Month, header.dateStart.Day);
+ gbDebug("%02d:%02d:%02d ", header.timeStart.Hour, header.timeStart.Minute, header.timeStart.Second);
+ gbDebug("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", header.TotalPoint, header.TotalTime / 10, header.TotalDistance, header.LapCnts);
+ gbDebug("Index/StartPt:%u ", header.gh_ptrec.Index);
+ gbDebug("LapIndex/EndPt:%u ", header.gh_laprec.LapIndex);
+ gbDebug("DataType:0x%x\n", header.DataType);
}
/*
db_lap.EndPt = be_read32(dblap+37);
if (global_opts.debug_level > 1) {
- printf(" lap[%d] AccruedTime:%us TotalTime:%us TotalDist:%um", lap, db_lap.AccruedTime, db_lap.TotalTime / 10, db_lap.TotalDistance);
- printf(" Calory:%d MaxSpeed:%u Hearth max:%d avg:%d ", db_lap.Calory, db_lap.MaxSpeed, db_lap.MaxHeart, db_lap.AvgHeart);
- printf(" Alt min:%d max:%d", db_lap.MinAlti, db_lap.MaxAlti);
- printf(" Cadns avg:%d best:%d", db_lap.AvgCadns, db_lap.BestCadns);
- printf(" Power avg:%d Max:%d", db_lap.AvgPower, db_lap.MaxPower);
- printf(" MultisportIndex:%d", db_lap.MultiSportIndex);
- printf(" StartPt:%u EndPt:%u\n", db_lap.StartPt, db_lap.EndPt);
+ gbDebug(" lap[%d] AccruedTime:%us TotalTime:%us TotalDist:%um", lap, db_lap.AccruedTime, db_lap.TotalTime / 10, db_lap.TotalDistance);
+ gbDebug(" Calory:%d MaxSpeed:%u Hearth max:%d avg:%d ", db_lap.Calory, db_lap.MaxSpeed, db_lap.MaxHeart, db_lap.AvgHeart);
+ gbDebug(" Alt min:%d max:%d", db_lap.MinAlti, db_lap.MaxAlti);
+ gbDebug(" Cadns avg:%d best:%d", db_lap.AvgCadns, db_lap.BestCadns);
+ gbDebug(" Power avg:%d Max:%d", db_lap.AvgPower, db_lap.MaxPower);
+ gbDebug(" MultisportIndex:%d", db_lap.MultiSportIndex);
+ gbDebug(" StartPt:%u EndPt:%u\n", db_lap.StartPt, db_lap.EndPt);
}
}
free(track_payload);
if (global_opts.debug_level > 1) {
- printf("Lap Trainheader: %02d-%02d-%02d ", laptrain_header.dateStart.Year, laptrain_header.dateStart.Month, laptrain_header.dateStart.Day);
- printf("%02d:%02d:%02d ", laptrain_header.timeStart.Hour, laptrain_header.timeStart.Minute, laptrain_header.timeStart.Second);
- printf("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", laptrain_header.TotalPoint, laptrain_header.TotalTime / 10, laptrain_header.TotalDistance, laptrain_header.LapCnts);
- printf("StartPt:%u ", laptrain_header.gh_ptrec.StartPt);
- printf("EndPt:%u ", laptrain_header.gh_laprec.EndPt);
- printf("DataType:0x%x\n", laptrain_header.DataType);
+ gbDebug("Lap Trainheader: %02d-%02d-%02d ", laptrain_header.dateStart.Year, laptrain_header.dateStart.Month, laptrain_header.dateStart.Day);
+ gbDebug("%02d:%02d:%02d ", laptrain_header.timeStart.Hour, laptrain_header.timeStart.Minute, laptrain_header.timeStart.Second);
+ gbDebug("Total(points:%6u time:%6us dist:%9um) LapCnts:%5d ", laptrain_header.TotalPoint, laptrain_header.TotalTime / 10, laptrain_header.TotalDistance, laptrain_header.LapCnts);
+ gbDebug("StartPt:%u ", laptrain_header.gh_ptrec.StartPt);
+ gbDebug("EndPt:%u ", laptrain_header.gh_laprec.EndPt);
+ gbDebug("DataType:0x%x\n", laptrain_header.DataType);
}
int recpoints_in_package = laptrain_header.gh_laprec.EndPt - laptrain_header.gh_ptrec.StartPt + 1;
// qDebug() << "DateTime2:" << gpsDateTime.toString();
// }
if (global_opts.debug_level > 1) {
- printf(" recpoint[%2d] Lat:%f Long:%f Alt:%dm", recpoint, (double)((int32_t) point.Latitude) / 1000000.0, (double)((int32_t) point.Longitude) / 1000000.0, point.Altitude);
- printf(" Speed:%f HR:%d", (double) point.Speed / 100, point.HeartRate);
- printf(" Time:%u Cadence:%d", point.IntervalTime, point.Cadence);
- printf(" PwrCadense:%d Power:%d\n", point.PwrCadence, point.Power);
+ gbDebug(" recpoint[%2d] Lat:%f Long:%f Alt:%dm", recpoint, (double)((int32_t) point.Latitude) / 1000000.0, (double)((int32_t) point.Longitude) / 1000000.0, point.Altitude);
+ gbDebug(" Speed:%f HR:%d", (double) point.Speed / 100, point.HeartRate);
+ gbDebug(" Time:%u Cadence:%d", point.IntervalTime, point.Cadence);
+ gbDebug(" PwrCadense:%d Power:%d\n", point.PwrCadence, point.Power);
}
auto* wpt = new Waypoint(); // waypt_new();
GlobalsatSportFormat::route_read()
{
if (global_opts.debug_level > 1) {
- printf(MYNAME " route_read() TODO\n");
+ gbDebug("route_read() TODO\n");
}
}
GlobalsatSportFormat::read()
{
if (global_opts.debug_level > 1) {
- printf(MYNAME " read()\n");
+ gbDebug("read()\n");
}
if (global_opts.masked_objective & WPTDATAMASK) {
}
if (!(global_opts.masked_objective &
(WPTDATAMASK | TRKDATAMASK | RTEDATAMASK | POSNDATAMASK))) {
- fatal(MYNAME ": Nothing to do.\n");
+ gbFatal("Nothing to do.\n");
}
}
void serial_init(const char* fname);
void serial_deinit();
int serial_recv_byte() const;
- void serial_write_byte(uint8_t byte) const;
+ void serial_write_byte(uint8_t byte);
int recv_byte();
void write_byte(uint8_t byte);
void globalsat_write_package(uint8_t* payload, uint32_t size);
void GoogleTakeoutFormat::takeout_fatal(const QString& message) {
- fatal(FatalMsg() << MYNAME << ": " << message);
+ gbFatal(FatalMsg() << message);
}
void GoogleTakeoutFormat::takeout_warning(const QString& message) {
- Warning() << MYNAME << ": " << message;
+ Warning() << message;
}
/* create a waypoint from late7/lone7 and optional metadata */
}
}
if (global_opts.debug_level >= 1) {
- Debug(1) << MYNAME << ": Processed " << items << " items: " <<
+ Debug(1) << "Processed " << items << " items: " <<
place_visits << " " << PLACE_VISIT << ", " << activity_segments <<
" " << ACTIVITY_SEGMENT << " (" << points << " points total)";
}
private:
/* Constants */
- static constexpr char MYNAME[] = "Google Takeout";
static constexpr char TIMELINE_OBJECTS[] = "timelineObjects";
static constexpr char16_t PLACE_VISIT[] = u"placeVisit";
static constexpr char16_t ACTIVITY_SEGMENT[] = u"activitySegment";
static Waypoint* takeout_waypoint(int lat_e7, int lon_e7, const QString* shortname, const QString* description, const QString* start_str);
static bool track_maybe_add_wpt(route_head* route, Waypoint* waypoint);
static void title_case(QString& title);
- void add_place_visit(const QJsonObject& placeVisit);
- int add_activity_segment(const QJsonObject& activitySegment);
+ static void add_place_visit(const QJsonObject& placeVisit);
+ static int add_activity_segment(const QJsonObject& activitySegment);
/* Data Members */
#include "src/core/xmltag.h" // for xml_tag, fs_xml, fs_xml_alloc, free_gpx_extras
-#define MYNAME "GPX"
#ifndef CREATOR_NAME_URL
# define CREATOR_NAME_URL "GPSBabel - https://www.gpsbabel.org"
#endif
// but that feature is so obscure and used in so few outputs that
// there's no reason to alarm the user. Just silently disregard
// category names that don't map cleanly.
- // warning(MYNAME ": Unable to convert category \"%s\"!\n", CSTR(text));
+ // gbWarning("Unable to convert category \"%s\"!\n", CSTR(text));
}
break;
case tag_type::garmin_wpt_addr:
// It's a good thing 0, 0.0, 0.0.0 aren't valid gpx versions,
// normalization makes them null.
if (gpx_write_version.isNull() || (gpx_write_version < gpx_1_0)) {
- fatal(FatalMsg() << MYNAME ": gpx version number"
+ gbFatal(FatalMsg() << "gpx version number"
<< gpx_write_version << "not valid.");
}
}
if (reader->hasError()) {
- fatal(FatalMsg() << MYNAME << "Read error:" << reader->errorString()
+ gbFatal(FatalMsg() << "Read error:" << reader->errorString()
<< "File:" << iqfile->fileName()
<< "Line:" << reader->lineNumber()
<< "Column:" << reader->columnNumber());
#include "src/core/datetime.h" // for DateTime
-#define MYNAME "GTM"
#define EPOCH89DIFF 631065600
/* was 631076400 but that seems to include a three-hour bias */
#define WAYPOINTSTYLES \
}
if (indatum == -1) {
- warning(MYNAME ": Unsupported datum (%d), won't convert to WGS84\n", n);
+ gbWarning("Unsupported datum (%d), won't convert to WGS84\n", n);
}
}
void
GtmFormat::rd_init(const QString& fname)
{
- file_in = gbfopen_le(fname, "rb", MYNAME);
+ file_in = gbfopen_le(fname, "rb");
int version = fread_integer(file_in);
QString name = fread_fixedstring(file_in, 10);
if (version == -29921) {
- fatal(MYNAME ": Uncompress the file first\n");
+ gbFatal("Uncompress the file first\n");
}
if (name != "TrackMaker") {
- fatal(MYNAME ": Invalid file format\n");
+ gbFatal("Invalid file format\n");
}
if (version != 211) {
- fatal(MYNAME ": Invalid format version\n");
+ gbFatal("Invalid format version\n");
}
/* Header */
};
track_disp_all(count_track_styles_lambda, nullptr, nullptr);
- file_out = gbfopen_le(fname, "wb", MYNAME); /* little endian */
+ file_out = gbfopen_le(fname, "wb"); /* little endian */
/* Header */
fwrite_integer(file_out, 211);
// If ts_count != real_track_list.size() we don't know how to line up
// the tracklogs, and the real tracks, with the tracklog styles.
if (ts_count != real_track_list.size()) {
- warning(MYNAME ": The number of tracklog entries with the new flag "
+ gbWarning("The number of tracklog entries with the new flag "
"set doesn't match the number of tracklog style entries.\n"
" This is unexpected and may indicate a malformed input file.\n"
" As a result the track names may be incorrect.\n");
#include "xmlgeneric.h" // for xml_deinit, xml_init, xml_read
-#define MYNAME "gtc"
-
const QStringList GtrnctrFormat::gtc_tags_to_ignore = {
"TrainingCenterDatabase",
"CourseFolder",
void
GtrnctrFormat::wr_init(const QString& fname)
{
- ofd = gbfopen(fname, "w", MYNAME);
+ ofd = gbfopen(fname, "w");
if (opt_sport) {
for (unsigned int i = 0; i < std::size(gtc_sportlist); i++) {
#include <cmath> // for floor
#include <cstdint> // for int8_t
-#define MYNAME "height"
#if FILTERS_ENABLED
{
/* sanity checks to prevent segfault on bad data */
if ((lat > 90.0) || (lat < -90.0)) {
- fatal(MYNAME ": Invalid latitude value (%f)\n", lat);
+ gbFatal("Invalid latitude value (%f)\n", lat);
}
if ((lon > 180.0) || (lon < -180.0)) {
- fatal(MYNAME ": Invalid longitude value (%f)\n", lon);
+ gbFatal("Invalid longitude value (%f)\n", lon);
}
auto ilat = static_cast<int>(floor((90.0+lat)/geoid_grid_deg));
{
addf = 0.0;
if (addopt) {
- if (parse_distance(addopt, &addf, 1.0, MYNAME) == 0) {
- fatal(MYNAME ": No height specified with add option.");
+ if (parse_distance(addopt, &addf, 1.0) == 0) {
+ gbFatal("No height specified with add option.\n");
}
}
}
#include "src/core/xmltag.h" // for xml_findfirst, xml_tag, xml_attribute, fs_xml, xml_findnext
-#define MYNAME "HTML"
-
void
HtmlFormat::wr_init(const QString& fname)
{
file_out = new gpsbabel::TextStream;
- file_out->open(fname, QIODevice::WriteOnly, MYNAME);
+ file_out->open(fname, QIODevice::WriteOnly);
mkshort_handle = new MakeShort;
static const QRegularExpression re("^(?:ddd|dmm|dms)$");
if (re.match(opt_degformat).hasMatch()) {
degformat = opt_degformat.get().at(2).toLatin1();
} else {
- fatal(MYNAME ": Unrecognized degformat %s, expected 'ddd', 'dmm' or 'dms'.\n", qPrintable(opt_degformat));
+ gbFatal("Unrecognized degformat %s, expected 'ddd', 'dmm' or 'dms'.\n", gbLogCStr(opt_degformat));
}
if (opt_altunits.get().startsWith('f')) {
} else if (opt_altunits.get().startsWith('m')) {
altunits = 'm';
} else {
- fatal(MYNAME ": Unrecognized altunits %s, expected 'f' for feet or 'm' for meters.\n", qPrintable(opt_altunits));
+ gbFatal("Unrecognized altunits %s, expected 'f' for feet or 'm' for meters.\n", gbLogCStr(opt_altunits));
}
}
#include <cstring> // for strncpy
#include <numbers> // for inv_pi, pi
-#include "defs.h" // for Waypoint, be_read32, be_read16, be_write32, fatal, be_write16, route_head, track_add_wpt
+#include "defs.h" // for Waypoint, be_read32, be_read16, be_write32, gbFatal, be_write16, route_head, track_add_wpt
#include "mkshort.h" // for MakeShort
#include "src/core/datetime.h" // for DateTime
-#define MYNAME "humminbird"
-
#define WPT_NAME_LEN 12
#define RTE_NAME_LEN 20
#define TRK_NAME_LEN 20
void
HumminbirdBase::humminbird_rd_init(const QString& fname)
{
- fin_ = gbfopen_be(fname, "rb", MYNAME);
+ fin_ = gbfopen_be(fname, "rb");
wpt_num_to_wpt_hash.clear();
}
static_assert(sizeof(w) == 32);
if (! gbfread(&w, 1, sizeof(w), fin)) {
- fatal(MYNAME ": Unexpected end of file!\n");
+ gbFatal("Unexpected end of file!\n");
}
/* Fix endianness - these are now BE */
static_assert(sizeof(hrte) == 132);
if (! gbfread(&hrte, 1, sizeof(hrte), fin)) {
- fatal(MYNAME ": Unexpected end of file!\n");
+ gbFatal("Unexpected end of file!\n");
}
hrte.time = be_read32(&hrte.time);
static_assert(sizeof(th) == 64);
if (! gbfread(&th, 1, sizeof(th), fin)) {
- fatal(MYNAME ": Unexpected end of file reading header!\n");
+ gbFatal("Unexpected end of file reading header!\n");
}
th.trk_num = be_read16(&th.trk_num);
}
if (th.num_points > max_points) {
- fatal(MYNAME ": Too many track points! (%d)\n", th.num_points);
+ gbFatal("Too many track points! (%d)\n", th.num_points);
}
/* num_points is actually one too big, because it includes the value in
freak-value filter below looks at points[i+1] */
auto* points = new humminbird_trk_point_t[th.num_points]();
if (! gbfread(points, sizeof(humminbird_trk_point_t), th.num_points-1, fin)) {
- fatal(MYNAME ": Unexpected end of file reading points!\n");
+ gbFatal("Unexpected end of file reading points!\n");
}
int32_t accum_east = th.start_east;
char namebuf[TRK_NAME_LEN];
if (! gbfread(&th, 1, sizeof(th), fin)) {
- fatal(MYNAME ": Unexpected end of file reading header!\n");
+ gbFatal("Unexpected end of file reading header!\n");
}
th.trk_num = be_read16(&th.trk_num);
int max_points = (file_len - (sizeof(th) + sizeof(uint32_t) + TRK_NAME_LEN)) / sizeof(humminbird_trk_point_old_t);
if (th.num_points > max_points) {
- fatal(MYNAME ": Too many track points! (%d)\n", th.num_points);
+ gbFatal("Too many track points! (%d)\n", th.num_points);
}
/* num_points is actually one too big, because it includes the value in
freak-value filter below looks at points[i+1] */
auto* points = new humminbird_trk_point_old_t[th.num_points]();
if (! gbfread(points, sizeof(humminbird_trk_point_old_t), th.num_points-1, fin)) {
- fatal(MYNAME ": Unexpected end of file reading points!\n");
+ gbFatal("Unexpected end of file reading points!\n");
}
int32_t accum_east = th.start_east;
humminbird_read_track_old(fin_);
return; /* Don't continue. The rest of the file is all zeores */
default:
- fatal(MYNAME ": Invalid record header \"0x%08X\" (no or unknown humminbird file)!\n", signature);
+ gbFatal("Invalid record header \"0x%08X\" (no or unknown humminbird file)!\n", signature);
}
}
}
void
HumminbirdBase::humminbird_wr_init(const QString& fname)
{
- fout_ = gbfopen_be(fname, "wb", MYNAME);
+ fout_ = gbfopen_be(fname, "wb");
wptname_sh = new MakeShort;
if (!wpt_id_to_wpt_num_hash.contains(id)) {
// This should not occur, we just scanned all waypoints and routes.
- warning("Missing waypoint reference in route, point dropped from route.");
+ gbWarning("Missing waypoint reference in route, point dropped from route.\n");
return;
}
humrte->points[humrte->count] = wpt_id_to_wpt_num_hash.value(id);
humrte->count++;
} else {
- warning(MYNAME ": Sorry, routes are limited to %d points!\n", MAX_RTE_POINTS);
- fatal(MYNAME ": You can use our simplify filter to reduce the number of route points.\n");
+ gbWarning("Sorry, routes are limited to %d points!\n", MAX_RTE_POINTS);
+ gbFatal("You can use our simplify filter to reduce the number of route points.\n");
}
}
-#define MYNAME "IGC"
#define HDRMAGIC "IGCHDRS"
#define HDRDELIM "~"
#define DATEMAGIC "IGCDATE"
}
if (len < 3 || c[0] < 'A' || c[0] > 'Z') {
- warning(MYNAME " bad input record: '%s'\n", c);
+ gbWarning("bad input record: '%s'\n", c);
return rec_bad;
}
return (igc_rec_type_t) c[0];
{
char* ibuf;
- file_in = gbfopen(fname, "r", MYNAME);
+ file_in = gbfopen(fname, "r");
// File must begin with a manufacturer/ID record
if (get_record(&ibuf) != rec_manuf_id || sscanf(ibuf, "A%3[A-Z]", manufacturer) != 1) {
- fatal(MYNAME ": %s is not an IGC file\n", qPrintable(fname));
+ gbFatal("%s is not an IGC file\n", gbLogCStr(fname));
}
}
&day, &month, &year,
&hour, &minute, &second,
flight_date, task_num, &num_tp, task_desc) < 9) {
- fatal(MYNAME ": task id (C) record parse error A. \n'%s'", rec);
+ gbFatal("task id (C) record parse error A. \n'%s'\n", rec);
}
task_num[4] = '\0';
if (year < 70) {
}
creation = QDateTime(QDate(year, month, day), QTime(hour, minute, second), QtUTC);
if (!creation.isValid()) {
- fatal(MYNAME ": bad date time\n%s\n", rec);
+ gbFatal("bad date time\n%s\n", rec);
}
// Create a route to store the task data in.
if (sscanf(rec, "C%2u%2u%3u%1[NS]%3u%2u%3u%1[WE]%78[^\r]\r\n",
&lat_deg, &lat_min, &lat_frac, lat_hemi,
&lon_deg, &lon_min, &lon_frac, lon_hemi, tmp_str) < 8) {
- fatal(MYNAME ": task waypoint (C) record parse error\n%s", rec);
+ gbFatal("task waypoint (C) record parse error\n%s\n", rec);
}
auto* wpt = new Waypoint;
break;
default:
- fatal(MYNAME ": task id (C) record internal error B\n%s", rec);
+ gbFatal("task id (C) record internal error B\n%s\n", rec);
break;
}
while (true) {
if (global_opts.debug_level >= 8) {
- printf(MYNAME ": Processing IGC file line %i\n", current_line);
+ gbDebug("Processing IGC file line %i\n", current_line);
}
igc_rec_type_t rec_type = get_record(&ibuf);
current_line++;
switch (rec_type) {
case rec_manuf_id:
// Manufacturer/ID record already found in rd_init().
- warning(MYNAME ": duplicate manufacturer/ID record\n");
+ gbWarning("duplicate manufacturer/ID record\n");
break;
case rec_header:
// Get the header sub type
if (sscanf(ibuf, "H%*1[FOPS]%3s", tmp_str) != 1) {
- fatal(MYNAME ": header (H) record parse error\n%s\n%s\n", ibuf, tmp_str);
+ gbFatal("header (H) record parse error\n%s\n%s\n", ibuf, tmp_str);
}
// Optional long name of record sub type is followed by a
// colon. Actual header data follows that.
int month;
int year;
if (sscanf(hdr_data, "%2d%2d%2d", &day, &month, &year) != 3) {
- fatal(MYNAME ": date (H) record parse error\n'%s'\n", ibuf);
+ gbFatal("date (H) record parse error\n'%s'\n", ibuf);
}
if (year < 70) {
year += 2000;
}
date = QDate(year, month, day);
if (!date.isValid()) {
- fatal(MYNAME ": bad date\n%s\n", ibuf);
+ gbFatal("bad date\n%s\n", ibuf);
}
} else {
// Store other header data in the track descriptions
case rec_fix: {
// Date must appear in file before the first fix record
if (!date.isValid()) {
- fatal(MYNAME ": bad date\n");
+ gbFatal("bad date\n");
}
// Create a track for pressure altitude waypoints
if (!pres_head) {
&hours, &mins, &secs, &lat_deg, &lat_min, &lat_frac,
lat_hemi, &lon_deg, &lon_min, &lon_frac, lon_hemi,
&validity, &pres_alt, &gnss_alt) != 14) {
- fatal(MYNAME ": fix (B) record parse error\n%s\n", ibuf);
+ gbFatal("fix (B) record parse error\n%s\n", ibuf);
}
pres_wpt = new Waypoint;
tod = QTime(hours, mins, secs);
if (!tod.isValid()) {
- fatal(MYNAME ": bad time\n%s\n", ibuf);
+ gbFatal("bad time\n%s\n", ibuf);
}
// Increment date if we pass midnight UTC
if (!ext_types_list.isEmpty()) {
auto* fsdata = new igc_fsdata;
if (global_opts.debug_level >= 7) {
- printf(MYNAME ": Record: %s\n",qPrintable(ibuf_q));
+ gbDebug("Record: %s\n",gbLogCStr(ibuf_q));
}
if (global_opts.debug_level >= 6) {
- printf(MYNAME ": Adding extension data:");
+ gbDebug("Adding extension data:");
}
for (const auto& [name, ext, start, len, factor] : ext_types_list) {
double ext_data = ibuf_q.mid(start,len).toInt() / factor;
fsdata->set_value(ext, ext_data, pres_wpt);
if (global_opts.debug_level >= 6) {
- printf(" %s:%f", qPrintable(name), ext_data);
+ gbDebug(" %s:%f", gbLogCStr(name), ext_data);
}
}
if (global_opts.debug_level >= 6) {
- printf("\n");
+ gbDebug("\n");
}
pres_wpt->fs.FsChainAdd(fsdata);
}
case rec_log_book:
// Get the log book sub type
if (sscanf(ibuf, "L%3s", tmp_str) != 1) {
- fatal(MYNAME ": log book (L) record parse error\n'%s'\n", ibuf);
+ gbFatal("log book (L) record parse error\n'%s'\n", ibuf);
}
if (strcmp(tmp_str, "PFC") == 0) {
break;
} else if (global_opts.debug_level >= 5) {
if (strcmp(tmp_str, "OOI") == 0) {
- printf(MYNAME ": Observer Input> %s\n", ibuf + 4);
+ gbDebug("Observer Input> %s\n", ibuf + 4);
} else if (strcmp(tmp_str, "PLT") == 0) {
- printf(MYNAME ": Pilot Input> %s\n", ibuf + 4);
+ gbDebug("Pilot Input> %s\n", ibuf + 4);
} else if (strcmp(tmp_str, manufacturer) == 0) {
- printf(MYNAME ": Manufacturer Input> %s\n", ibuf + 4);
+ gbDebug("Manufacturer Input> %s\n", ibuf + 4);
} else {
- printf(MYNAME ": Anonymous Input> %s\n", ibuf + 1);
+ gbDebug("Anonymous Input> %s\n", ibuf + 1);
}
}
break;
}
}
if (global_opts.debug_level >= 1) {
- printf(MYNAME ": I record: %s\n" MYNAME ": Extensions present: %s\n", qPrintable(ibuf_q),
- qPrintable(present_extensions.join(' ')));
+ gbDebug("I record: %s\n", gbLogCStr(ibuf_q));
+ gbDebug("Extensions present: %s\n", gbLogCStr(present_extensions.join(' ')));
}
if (global_opts.debug_level >= 2) {
- printf(MYNAME ": Non-excluded extensions defined in I record:\n");
- printf(MYNAME ": (Note: IGC records are one-initialized. QStrings are zero-initialized.)\n");
+ gbDebug("Non-excluded extensions defined in I record:\n");
+ gbDebug("(Note: IGC records are one-initialized. QStrings are zero-initialized.)\n");
for (const auto& [name, ext, begin, len, factor] : ext_types_list) {
- printf(MYNAME ": Extension %s (%i): Begin: %i; Length: %i\n", qPrintable(name), int(ext), begin, len);
+ gbDebug(" Extension %s (%i): Begin: %i; Length: %i\n", gbLogCStr(name), int(ext), begin, len);
}
if (global_opts.debug_level >= 3) {
- printf(MYNAME ": Unsupported extensions (I will not ingest these, they are unsupported):\t%s\n",
- qPrintable(unsupported_extensions.join(' ')));
- printf(MYNAME ": Supported extensions (These are present in the I record and supported):\t%s\n",
- qPrintable(supported_extensions.join(' ')));
+ gbDebug("Unsupported extensions (I will not ingest these, they are unsupported):\t%s\n",
+ gbLogCStr(unsupported_extensions.join(' ')));
+ gbDebug("Supported extensions (These are present in the I record and supported):\t%s\n",
+ gbLogCStr(supported_extensions.join(' ')));
}
}
}
default:
case rec_bad:
- fatal(MYNAME ": failure reading file\n");
+ gbFatal("failure reading file\n");
break;
}
}
char str[18];
if (snprintf(str, sizeof(str), "%02ld%05ld%c%03ld%05ld%c",
lat_digits.quot, lat_digits.rem, lat_hemi, lon_digits.quot, lon_digits.rem, lon_hemi) != 17) {
- fatal(MYNAME ": Bad waypoint format '%s'\n", str);
+ gbFatal("Bad waypoint format '%s'\n", str);
}
return str;
}
{
QByteArray str = dt.toUTC().toString(u"ddMMyy").toUtf8();
if (str.size() != 6) {
- fatal(MYNAME ": Bad date format '%s'\n", str.constData());
+ gbFatal("Bad date format '%s'\n", str.constData());
}
return str;
}
{
QByteArray str = tod.toUTC().toString(u"hhmmss").toUtf8();
if (str.size() != 6) {
- fatal(MYNAME ": Bad time of day format '%s'\n", str.constData());
+ gbFatal("Bad time of day format '%s'\n", str.constData());
}
return str;
}
// Date in header record is that of the first fix record
date = track->waypoint_list.front()->GetCreationTime();
if (!date.isValid()) {
- fatal(MYNAME ": Bad track timestamp\n");
+ gbFatal("Bad track timestamp\n");
}
} else {
// This is a bit silly, there aren't any tracks!
int num_tps = rte->rte_waypt_ct() - 2;
if (num_tps < 0) {
- fatal(MYNAME ": Empty task route\n");
+ gbFatal("Empty task route\n");
}
// See if the takeoff and landing waypoints are there or if we need to
// generate them.
num_tps--;
}
if (num_tps < 0) {
- fatal(MYNAME ": Too few waypoints in task route\n");
+ gbFatal("Too few waypoints in task route\n");
} else if (num_tps > 99) {
- fatal(MYNAME ": Too much waypoints (more than 99) in task route.\n");
+ gbFatal("Too much waypoints (more than 99) in task route.\n");
}
// Gather data to write to the task identification (first) record
gpsbabel::DateTime rte_time = wpt->GetCreationTime().isValid() ? wpt->GetCreationTime() : current_time();
{
gpsbabel::DateTime tt = wpt->GetCreationTime();
if (!tt.isValid()) {
- fatal(MYNAME ": Bad track timestamp\n");
+ gbFatal("Bad track timestamp\n");
}
if (unknown_alt == pres_alt) {
} while (alt_diff > -10.0);
gpsbabel::DateTime pres_time = (*std::prev(wpt_rit))->GetCreationTime();
if (global_opts.debug_level >= 1) {
- printf(MYNAME ": pressure landing time %s\n", CSTR(pres_time.toPrettyString()));
+ gbDebug("pressure landing time %s\n", CSTR(pres_time.toPrettyString()));
}
// Deduce the landing time from the GNSS altitude track based on
radtometers(gcdist(wpt->position(), (*wpt_rit)->position())) /
(0.001 * deltat_msec);
if (global_opts.debug_level >= 2) {
- printf(MYNAME ": speed=%.2fm/s\n", speed);
+ gbDebug("speed=%.2fm/s\n", speed);
}
} while (speed < 2.5);
gpsbabel::DateTime gnss_time = (*std::prev(wpt_rit))->GetCreationTime();
if (global_opts.debug_level >= 1) {
- printf(MYNAME ": gnss landing time %s\n", CSTR(gnss_time.toPrettyString()));
+ gbDebug("gnss landing time %s\n", CSTR(gnss_time.toPrettyString()));
}
// Time adjustment is difference between the two estimated landing times
int time_diff = gnss_time.secsTo(pres_time);
if (15 * 60 < abs(time_diff)) {
- warning(MYNAME ": excessive time adjustment %ds\n", time_diff);
+ gbWarning("excessive time adjustment %ds\n", time_diff);
}
return time_diff;
}
time_adj = 0;
}
if (global_opts.debug_level >= 1) {
- printf(MYNAME ": adjusting time by %ds\n", time_adj);
+ gbDebug("adjusting time by %ds\n", time_adj);
}
// Iterate through waypoints in both tracks simultaneously
Interpolater interpolater;
void IgcFormat::wr_init(const QString& fname)
{
- file_out = gbfopen(fname, "wb", MYNAME);
+ file_out = gbfopen(fname, "wb");
}
void IgcFormat::wr_deinit()
ret = 1;
break;
default:
- warning("igc.h: IgcFormat::get_ext_factor(): unknown extension (%i), returning factor of zero.\n",int(type));
+ gbWarning("igc.h: IgcFormat::get_ext_factor(): unknown extension (%i), returning factor of zero.\n",int(type));
break;
}
return ret;
ret = gfo;
break;
default:
- fatal("igc.h: igc_fsdata::get_value(IgcFormat::igc_ext_type_t defn_type): Invalid igc_ext_type\n");
+ gbFatal("igc.h: igc_fsdata::get_value(IgcFormat::igc_ext_type_t defn_type): Invalid igc_ext_type\n");
break;
}
return ret;
ret = gfo;
break;
default:
- fatal("igc.h: igc_fsdata::get_value(KmlFormat::wp_field defn_type): Invalid wp_field\n");
+ gbFatal("igc.h: igc_fsdata::get_value(KmlFormat::wp_field defn_type): Invalid wp_field\n");
break;
}
return ret;
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
-#include "defs.h" // for fatal, warning
+#include "defs.h" // for gbFatal, gbWarning
#include "inifile.h"
#include "src/core/file.h" // for File
#include <QByteArray> // for QByteArray
#include <QtGlobal> // for qEnvironmentVariable, qPrintable
#include <utility>
-#define MYNAME "inifile"
struct inifile_t {
QHash<QString, InifileSection> sections;
if (QFile(envstr).open(QIODevice::ReadOnly)) {
return envstr;
}
- warning("WARNING: GPSBabel-inifile, defined in environment, NOT found!\n");
+ gbWarning("WARNING: GPSBabel-inifile, defined in environment, NOT found!\n");
return res;
}
QString name = find_gpsbabel_inifile(""); // Check in current directory first.
}
static void
-inifile_load_file(QTextStream* stream, inifile_t* inifile, const char* myname)
+inifile_load_file(QTextStream* stream, inifile_t* inifile)
{
QString buf;
InifileSection section;
section_name = buf.mid(1, buf.indexOf(']') - 1).trimmed();
}
if (section_name.isEmpty()) {
- fatal("%s: invalid section header '%s' in '%s'.\n", myname, qPrintable(section_name),
- qPrintable(inifile->source));
+ gbFatal("invalid section header '%s' in '%s'.\n", gbLogCStr(section_name),
+ gbLogCStr(inifile->source));
}
// form lowercase key to implement CaseInsensitive matching.
section = inifile->sections.value(section_name);
} else {
if (section.name.isEmpty()) {
- fatal("%s: missing section header in '%s'.\n", myname,
- qPrintable(inifile->source));
+ gbFatal("missing section header in '%s'.\n",
+ gbLogCStr(inifile->source));
}
// Store key in lower case to implement CaseInsensitive matching.
/*
inifile_init:
reads inifile filename into memory
- myname represents the calling module
filename == NULL: try to open global gpsbabel.ini
*/
inifile_t*
-inifile_init(const QString& filename, const char* myname)
+inifile_init(const QString& filename)
{
QString name;
auto* result = new inifile_t;
QFileInfo fileinfo(file);
result->source = fileinfo.absoluteFilePath();
- inifile_load_file(&stream, result, myname);
+ inifile_load_file(&stream, result);
file.close();
return result;
/*
inifile_init:
reads inifile filename into memory
- myname represents the calling module
*/
-inifile_t* inifile_init(const QString& filename, const char* myname);
+inifile_t* inifile_init(const QString& filename);
void inifile_done(inifile_t* inifile);
bool inifile_has_section(const inifile_t* inifile, const QString& section);
#if FILTERS_ENABLED
-#define MYNAME "Interpolate filter"
void InterpolateFilter::process()
{
if ((opt_route && (route_count() == 0)) || (!opt_route && (track_count() == 0))) {
- fatal(FatalMsg() << MYNAME ": Found no routes or tracks to operate on.");
+ gbFatal(FatalMsg() << "Found no routes or tracks to operate on.");
}
auto process_rte_lambda = [this](const route_head* rte)->void {
double npts = 0;
if (opt_time) {
if (!timespan.has_value()) {
- fatal(FatalMsg() << MYNAME ": points must have valid times to interpolate by time!");
+ gbFatal(FatalMsg() << "points must have valid times to interpolate by time!");
}
// interpolate even if time is running backwards.
npts = std::abs(*timespan) / max_time_step;
npts = distspan / max_dist_step;
}
if (!std::isfinite(npts) || (npts >= INT_MAX)) {
- fatal(FatalMsg() << MYNAME ": interpolation interval too small!");
+ gbFatal(FatalMsg() << "interpolation interval too small!");
}
// Insert the required points
void InterpolateFilter::init()
{
if (opt_time && opt_dist) {
- fatal(FatalMsg() << MYNAME ": Can't interpolate on both time and distance.");
+ gbFatal(FatalMsg() << "Can't interpolate on both time and distance.");
} else if (opt_time && opt_route) {
- fatal(FatalMsg() << MYNAME ": Can't interpolate routes on time.");
+ gbFatal(FatalMsg() << "Can't interpolate routes on time.");
} else if (opt_time) {
max_time_step = 1000 * opt_time.get_result(); // milliseconds
if (max_time_step <= 0) {
- fatal(FatalMsg() << MYNAME ": interpolation time should be positive!");
+ gbFatal(FatalMsg() << "interpolation time should be positive!");
}
} else if (opt_dist) {
- if (parse_distance(opt_dist, &max_dist_step, kMetersPerMile, MYNAME) == 0) {
- fatal(FatalMsg() << MYNAME ": no distance specified with distance option!");
+ if (parse_distance(opt_dist, &max_dist_step, kMetersPerMile) == 0) {
+ gbFatal(FatalMsg() << "no distance specified with distance option!");
}
if (max_dist_step <= 0) {
- fatal(FatalMsg() << MYNAME ": interpolation distance should be positive!");
+ gbFatal(FatalMsg() << "interpolation distance should be positive!");
}
} else {
- fatal(FatalMsg() << MYNAME ": No interval specified.");
+ gbFatal(FatalMsg() << "No interval specified.");
}
}
i = 0;
}
}
- fatal("Failed to find a product inquiry response.\n");
+ gbFatal("Failed to find a product inquiry response.\n");
}
carry_on:
if (gps_category_transfer) {
ret = GPS_A101_Get(port);
if (!ret) {
- fatal("blah");
+ gbFatal("blah\n");
return PROTOCOL_ERROR;
}
continue;
}
if (wpt[i] == nullptr || ctk[j] == nullptr) {
- fatal("Internal error in GPS_Command_Send_Track_As_Course");
+ gbFatal("Internal error in GPS_Command_Send_Track_As_Course\n");
}
dist = gcgeodist(wpt[i]->lat, wpt[i]->lon, ctk[j]->lat, ctk[j]->lon);
if (dist < min_dist) {
}
if (wpt[i] == nullptr) {
- fatal("Internal error in GPS_Command_Send_Track_As_Course: no wpt");
+ gbFatal("Internal error in GPS_Command_Send_Track_As_Course: no wpt\n");
}
cpt[i+n_cpt] = GPS_Course_Point_New();
strncpy(cpt[i+n_cpt]->name, wpt[i]->cmnt,
int ret = libusb_bulk_transfer(udev, gusb_bulk_out_ep, buf, sz,
&transferred, TMOUT_B);
if (ret != LIBUSB_SUCCESS) {
- fatal("libusb_bulk_transfer failed. '%s'\n",
+ gbFatal("libusb_bulk_transfer failed. '%s'\n",
libusb_strerror(static_cast<enum libusb_error>(ret)));
}
if (transferred != (int) sz) {
- warning("Bad cmdsend transferred %d sz %zu\n", transferred, sz);
+ gbWarning("Bad cmdsend transferred %d sz %zu\n", transferred, sz);
}
return transferred;
if (udev != nullptr) {
int ret = libusb_release_interface(udev, 0);
if (ret != LIBUSB_SUCCESS) {
- warning("libusb_release_interface failed: %s\n",
+ gbWarning("libusb_release_interface failed: %s\n",
libusb_strerror(static_cast<enum libusb_error>(ret)));
}
libusb_close(udev);
break;
}
if (t-- <= 0) {
- fatal("Could not start session in a reasonable number of tries.\n");
+ gbFatal("Could not start session in a reasonable number of tries.\n");
}
}
return rv;
}
if (t-- <= 0) {
- fatal("Could not start session in a reasonable number of tries.\n");
+ gbFatal("Could not start session in a reasonable number of tries.\n");
}
}
return 0;
}
ret = libusb_open(dev, &udev);
if (ret != LIBUSB_SUCCESS) {
- fatal("libusb_open failed: %s\n",
+ gbFatal("libusb_open failed: %s\n",
libusb_strerror(static_cast<enum libusb_error>(ret)));
}
assert(udev != nullptr);
// devices will work only the first time after a reset.
ret = libusb_set_configuration(udev, 1);
if (ret != LIBUSB_SUCCESS) {
- fatal("libusb_set_configuration failed: %s\n",
+ gbFatal("libusb_set_configuration failed: %s\n",
libusb_strerror(static_cast<enum libusb_error>(ret)));
}
#endif
* kernel driver that bonds with the hardware.
*/
usb_get_driver_np(udev, 0, drvnm, sizeof(drvnm)-1);
- fatal("usb_set_configuration failed, probably because kernel driver '%s'\n is blocking our access to the USB device.\n"
+ gbFatal("usb_set_configuration failed, probably because kernel driver '%s'\n is blocking our access to the USB device.\n"
"For more information see https://www.gpsbabel.org/os/Linux_Hotplug.html\n", drvnm);
#else
- fatal("usb_set_configuration failed: %s\n", usb_strerror());
+ gbFatal("usb_set_configuration failed: %s\n", usb_strerror());
#endif
}
#endif
ret = libusb_claim_interface(udev, 0);
if (ret != LIBUSB_SUCCESS) {
- fatal("libusb_claim_interface failed: %s\n",
+ gbFatal("libusb_claim_interface failed: %s\n",
libusb_strerror(static_cast<enum libusb_error>(ret)));
}
*
* Rather than crash, we at least print
* a nastygram. Experiments with retrying various USB ops brought
- * no joy, so just call fatal and move on.
+ * no joy, so just call gbFatal and move on.
*/
struct libusb_config_descriptor* config;
ret = libusb_get_active_config_descriptor(dev, &config);
if (ret != LIBUSB_SUCCESS) {
- fatal("libusb_get_active_config_descriptor failed: %s\n",
+ gbFatal("libusb_get_active_config_descriptor failed: %s\n",
libusb_strerror(static_cast<enum libusb_error>(ret)));
}
if (config == nullptr) {
- fatal("Found USB device with no configuration.\n");
+ gbFatal("Found USB device with no configuration.\n");
}
for (int i = 0; i < config->bNumInterfaces; ++i) {
return;
}
- fatal("Could not identify endpoints on USB device.\n"
+ gbFatal("Could not identify endpoints on USB device.\n"
"Found endpoints Intr In 0x%x Bulk Out 0x%x Bulk In %0xx\n",
gusb_intr_in_ep, gusb_bulk_out_ep, gusb_bulk_in_ep);
}
struct libusb_device_descriptor desc;
int ret = libusb_get_device_descriptor(devs[i], &desc);
if (ret != LIBUSB_SUCCESS) {
- fatal("libusb_get_device_descriptor failed: %s\n",
+ gbFatal("libusb_get_device_descriptor failed: %s\n",
libusb_strerror(static_cast<enum libusb_error>(ret)));
}
if ((desc.idVendor == GARMIN_VID) &&
}
if (0 == found_devices) {
- fatal("Found no Garmin USB devices.\n");
+ gbFatal("Found no Garmin USB devices.\n");
} else if (req_unit_number >= found_devices) {
- fatal("usb unit number(%d) too high.\n"
+ gbFatal("usb unit number(%d) too high.\n"
"The unit number must be either\n"
"1) nonnegative and less than the number of garmin devices found(%d), or\n"
"2) negative to list the garmin devices found.\n",
// libusb_set_option(nullptr, LIBUSB_OPTION_LOG_LEVEL, 99);
int ret = libusb_init(nullptr);
if (ret != LIBUSB_SUCCESS) {
- fatal("libusb_init failed: %s\n",
+ gbFatal("libusb_init failed: %s\n",
libusb_strerror(static_cast<enum libusb_error>(ret)));
}
libusb_successfully_initialized = true;
#include <QString> // for QString
-#include "defs.h" // for case_ignore_strcmp, fatal, CSTR
+#include "defs.h" // for case_ignore_strcmp, gbFatal, CSTR
#include "jeeps/gpsdatum.h" // for GPS_ODatum, GPS_OEllipse, GPS_Datums, GPS_Ellipses, UKNG, GPS_SDatum_Alias, GPS_SDatum, GPS_DatumAliases, GPS_PDatum, GPS_PDatum_Alias
static constexpr bool use_exact_helmert_inverse = false;
int32_t datum = GPS_Lookup_Datum_Index("Palestine 1923");
if (datum < 0) {
- fatal("Unable to find Palestine 1923 in internal tables");
+ gbFatal("Unable to find Palestine 1923 in internal tables\n");
}
int32_t ellipse = GPS_Datums[datum].ellipse;
double phi, lambda, alt, a, b;
int32_t datum = GPS_Lookup_Datum_Index("Palestine 1923");
if (datum < 0) {
- fatal("Unable to find Palestine 1923 in internal tables");
+ gbFatal("Unable to find Palestine 1923 in internal tables\n");
}
int32_t ellipse = GPS_Datums[datum].ellipse;
}
WriteFile(wsd->comport, obuf, size, &len, NULL);
if (len != (DWORD) size) {
- fatal("Write error. Wrote %d of %d bytes.\n", (int)len, size);
+ gbFatal("Write error. Wrote %d of %d bytes.\n", (int)len, size);
}
return len;
}
rv = gusb_llops->llop_get_bulk(ibuf, sz);
break;
default:
- fatal("Unknown receiver state %d\n", receive_state);
+ gbFatal("Unknown receiver state %d\n", receive_state);
}
pkt_id = le_read16(&ibuf->gusb_pkt.pkt_id);
return;
}
}
- fatal("Unable to sync with Garmin USB device in %d attempts.", i);
+ gbFatal("Unable to sync with Garmin USB device in %d attempts.\n", i);
}
void
return;
}
}
- fatal("Unable to establish USB syncup\n");
+ gbFatal("Unable to establish USB syncup\n");
}
if (!DeviceIoControl(usb_handle, IOCTL_GARMIN_USB_INTERRUPT_IN, NULL, 0,
buf, GARMIN_USB_INTERRUPT_DATA_SIZE, &rxed, NULL)) {
GPS_Serial_Error("Ioctl");
- fatal("ioctl\n");
+ gbFatal("ioctl\n");
}
buf += rxed;
sz -= rxed;
WriteFile(usb_handle, obuf, sz, &rsz, NULL);
if (rsz != sz) {
- fatal("Error sending %zu bytes. Successfully sent %ld\n", sz, rsz);
+ gbFatal("Error sending %zu bytes. Successfully sent %ld\n", sz, rsz);
}
return rsz;
pdd->DevicePath);
if (usb_handle != INVALID_HANDLE_VALUE) {
- fatal("garmin_usb_start called while device already started.\n");
+ gbFatal("garmin_usb_start called while device already started.\n");
}
usb_handle = CreateFile(pdd->DevicePath, GENERIC_READ|GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
if (usb_handle == INVALID_HANDLE_VALUE) {
if (GetLastError() == ERROR_ACCESS_DENIED) {
- warning(
+ gbWarning(
"Exclusive access is denied. It's likely that something else such as\n"
"Garmin Lifetime Updater, Communicator, Basecamp, Nroute, Spanner,\n"
"Google Earth, or GPSGate already has control of the device\n");
if (!DeviceIoControl(usb_handle, IOCTL_GARMIN_USB_BULK_OUT_PACKET_SIZE,
NULL, 0, &usb_tx_packet_size, GARMIN_USB_INTERRUPT_DATA_SIZE,
&size, NULL)) {
- fatal("Couldn't get USB packet size.\n");
+ gbFatal("Couldn't get USB packet size.\n");
}
win_llops.max_tx_size = usb_tx_packet_size;
if (hdevinfo == INVALID_HANDLE_VALUE) {
GPS_Serial_Error("SetupDiGetClassDevs failed");
- warning("Is the Garmin USB driver installed?\n");
+ gbWarning("Is the Garmin USB driver installed?\n");
return 0;
}
&GARMIN_GUID,
req_unit_number, &devinterface)) {
GPS_Serial_Error("SetupDiEnumDeviceInterfaces");
- warning("Is the Garmin USB unit number %d powered up and connected?\nIs it really a USB unit? If it's serial, don't choose USB, choose serial.\nAre the Garmin USB drivers installed and functioning with other programs?\nIs it a storage based device like Nuvi, CO, or OR?\n If so, send GPX files to it, don't use this module.\n", un);
+ gbWarning("Is the Garmin USB unit number %d powered up and connected?\nIs it really a USB unit? If it's serial, don't choose USB, choose serial.\nAre the Garmin USB drivers installed and functioning with other programs?\nIs it a storage based device like Nuvi, CO, or OR?\n If so, send GPX files to it, don't use this module.\n", un);
return 0;
}
/* We've matched. Now start the specific unit. */
} else {
GPS_Serial_Error("SetupDiEnumDeviceInterfaces");
- warning("Is the Garmin USB unit number %d powered up and connected?\n", un);
+ gbWarning("Is the Garmin USB unit number %d powered up and connected?\n", un);
return 0;
}
}
#include "kml.h"
#include <cmath> // for fabs
-#include <cstdio> // for sscanf, printf
+#include <cstdio> // for sscanf, EOF
#include <optional> // for optional
#include <tuple> // for tuple, make_tuple
#define ICON_MULTI_TRK ICON_BASE "track-directional/track-0.png"
#define ICON_DIR ICON_BASE "track-directional/track-%1.png" // format string where next arg is rotational degrees.
-#define MYNAME "kml"
const QStringList KmlFormat::kml_tags_to_ignore = {
"kml",
// Note that color_seq may be outside this range if the cast from float to int fails.
int color_seq = static_cast<int>(kml_color_sequencer.seq) % (kml_color_limit * 6);
if (global_opts.debug_level >= 1) {
- printf(MYNAME ": kml_color_sequencer seq %f %d, step %f\n", kml_color_sequencer.seq, color_seq, kml_color_sequencer.step);
+ gbDebug("kml_color_sequencer seq %f %d, step %f\n", kml_color_sequencer.seq, color_seq, kml_color_sequencer.step);
}
if ((color_seq >= (0*kml_color_limit)) && (color_seq < (1*kml_color_limit))) {
kml_color_sequencer.color.bbggrr = kml_bgr_to_color(0, color_seq, kml_color_limit);
} else if ((color_seq >= (5*kml_color_limit)) && (color_seq < (6*kml_color_limit))) {
kml_color_sequencer.color.bbggrr = kml_bgr_to_color(6*kml_color_limit-color_seq, 0, kml_color_limit);
} else { // should not occur, but to be safe generate a legal color.
- warning(MYNAME ": Error in color conversion - using default color.\n");
+ gbWarning("Error in color conversion - using default color.\n");
kml_color_sequencer.color.bbggrr = kml_bgr_to_color(102, 102, 102);
}
// compute next color.
void KmlFormat::wpt_s(const QString& /*args*/, const QXmlStreamAttributes* /*attrs*/)
{
if (wpt_tmp) {
- fatal(MYNAME ": wpt_s: invalid kml file\n");
+ gbFatal("wpt_s: invalid kml file\n");
}
wpt_tmp = new Waypoint;
wpt_tmp_queued = false;
void KmlFormat::wpt_e(const QString& /*args*/, const QXmlStreamAttributes* /*attrs*/)
{
if (!wpt_tmp) {
- fatal(MYNAME ": wpt_e: invalid kml file\n");
+ gbFatal("wpt_e: invalid kml file\n");
}
if (wpt_tmp_queued) {
waypt_add(wpt_tmp);
void KmlFormat::wpt_name(const QString& args, const QXmlStreamAttributes* /*attrs*/)
{
if (!wpt_tmp) {
- fatal(MYNAME ": wpt_name: invalid kml file\n");
+ gbFatal("wpt_name: invalid kml file\n");
}
wpt_tmp->shortname = args;
}
void KmlFormat::wpt_desc(const QString& args, const QXmlStreamAttributes* /*attrs*/)
{
if (!wpt_tmp) {
- fatal(MYNAME ": wpt_desc: invalid kml file\n");
+ gbFatal("wpt_desc: invalid kml file\n");
}
wpt_tmp->description += args.trimmed();
}
void KmlFormat::wpt_time(const QString& args, const QXmlStreamAttributes* /*attrs*/)
{
if (!wpt_tmp) {
- fatal(MYNAME ": wpt_time: invalid kml file\n");
+ gbFatal("wpt_time: invalid kml file\n");
}
wpt_tmp->SetCreationTime(xml_parse_time(args));
}
trkpt->latitude = coords[1].toDouble();
trkpt->longitude = coords[0].toDouble();
} else {
- Warning() << MYNAME << ": malformed coordinates " << vec;
+ Warning() << "malformed coordinates " << vec;
}
track_add_wpt(trk_head, trkpt);
}
if (!trk_head->rte_waypt_empty()) {
qint64 timespan_ms = wpt_timespan_begin.msecsTo(wpt_timespan_end);
if (trk_head->rte_waypt_ct() < 2) {
- fatal(MYNAME ": attempt to interpolate TimeSpan with too few points.");
+ gbFatal("attempt to interpolate TimeSpan with too few points.\n");
}
qint64 ms_per_waypoint = timespan_ms / (trk_head->rte_waypt_ct() - 1);
foreach (Waypoint* trackpoint, trk_head->waypoint_list) {
// Check that for every temporal value (kml:when) in a kml:Track there is a position (kml:coord) value.
// Check that for every temporal value (kml:when) in a gx:Track there is a position (gx:coord) value.
if (gx_trk_times->size() != gx_trk_coords->size()) {
- fatal(MYNAME ": There were more coord elements than the number of when elements.\n");
+ gbFatal("There were more coord elements than the number of when elements.\n");
}
// In KML 2.3 kml:Track elements kml:coord and kml:when elements are not required to be in any order.
void KmlFormat::gx_trk_when(const QString& args, const QXmlStreamAttributes* /*attrs*/)
{
if (! gx_trk_times) {
- fatal(MYNAME ": gx_trk_when: invalid kml file\n");
+ gbFatal("gx_trk_when: invalid kml file\n");
}
gx_trk_times->append(xml_parse_time(args));
}
void KmlFormat::gx_trk_coord(const QString& args, const QXmlStreamAttributes* /*attrs*/)
{
if (! gx_trk_coords) {
- fatal(MYNAME ": gx_trk_coord: invalid kml file\n");
+ gbFatal("gx_trk_coord: invalid kml file\n");
}
double lat;
double alt;
int n = sscanf(CSTR(args), "%lf %lf %lf", &lon, &lat, &alt);
if (EOF != n && 2 != n && 3 != n) {
- fatal(MYNAME ": coord field decode failure on \"%s\".\n", qPrintable(args));
+ gbFatal("coord field decode failure on \"%s\".\n", gbLogCStr(args));
}
gx_trk_coords->append(std::make_tuple(n, lat, lon, alt));
}
unitsformatter->setunits(UnitsFormatter::units_t::aviation);
break;
default:
- fatal("Units argument '%s' should be 's' for statute units, 'm' for metric, 'n' for nautical or 'a' for aviation.\n", qPrintable(opt_units));
+ gbFatal("Units argument '%s' should be 's' for statute units, 'm' for metric, 'n' for nautical or 'a' for aviation.\n", gbLogCStr(opt_units));
break;
}
/*
force_heading = true;
break;
default:
- fatal("kml_output_point: unknown point type");
+ gbFatal("kml_output_point: unknown point type\n");
break;
}
style = "#route";
break;
default:
- fatal("kml_output_point: unknown point type");
+ gbFatal("kml_output_point: unknown point type\n");
break;
}
QString star_content;
if (rating < 0 || rating > 50 || rating % 5 != 0) {
- fatal("Bogus difficulty or terrain rating.");
+ gbFatal("Bogus difficulty or terrain rating.\n");
}
if (0 == rating % 10) {
writer->writeStartElement(QStringLiteral("gx:SimpleArrayData"));
writer->writeAttribute(QStringLiteral("name"), name);
if (global_opts.debug_level >= 3) {
- printf(MYNAME ": New KML SimpleArray: %s\n", qPrintable(name));
+ gbDebug("New KML SimpleArray: %s\n", gbLogCStr(name));
}
foreach (const Waypoint* wpt, header->waypoint_list) {
const auto* fs_igc = reinterpret_cast<igc_fsdata*>(wpt->fs.FsChainFind(kFsIGC));
if (fs_igc && fs_igc->get_value(member).has_value()) {
double value = fs_igc->get_value(member).value();
if (global_opts.debug_level >= 6) {
- printf(MYNAME ": Writing KML SimpleArray data: %s of %f\n", qPrintable(name), value);
+ gbDebug("Writing KML SimpleArray data: %s of %f\n", gbLogCStr(name), value);
}
writer->writeTextElement(QStringLiteral("gx:value"), QString::number(value));
// No igc_fsdata present, but we still need to write out the SimpleArray.
// This can happen when merging tracks with different sets of IGC extensions.
} else {
if (global_opts.debug_level >= 7) {
- printf(MYNAME ": Writing empty KML SimpleArray data for %s\n", qPrintable(name));
+ gbDebug("Writing empty KML SimpleArray data for %s\n", gbLogCStr(name));
}
writer->writeTextElement(QStringLiteral("gx:value"), QString());
}
break;
default:
- fatal("Bad member type");
+ gbFatal("Bad member type\n");
}
}
writer->writeEndElement(); // Close SimpleArrayData tag
#include <cinttypes> // for PRId64
#include <cmath> // for round, atan, exp, log, tan
-#include <cstdio> // for printf, sprintf, SEEK_CUR
+#include <cstdio> // for SEEK_CUR
#include <cstdint> // for int64_t
#include <cstdlib> // for abs
#include <numbers> // for pi
/* from waypt.c, we need to iterate over waypoints when extracting routes */
extern WaypointList* global_waypoint_list;
-#define MYNAME "Lowrance USR"
-
/* below couple of functions mostly borrowed from raymarine.c */
/* make waypoint shortnames unique */
}
void
-LowranceusrFormat::register_waypt(const Waypoint* wpt) const
+LowranceusrFormat::register_waypt(const Waypoint* wpt)
{
for (const Waypoint* cmp : std::as_const(*waypt_table)) {
if (same_points(wpt, cmp)) {
}
if (global_opts.debug_level >= 2) {
- printf(MYNAME " adding waypt %s (%s) to table at index %s\n",
- qPrintable(wpt->shortname), qPrintable(wpt->description), QByteArray::number(waypt_table->size()).constData());
+ gbDebug("adding waypt %s (%s) to table at index %s\n",
+ gbLogCStr(wpt->shortname), gbLogCStr(wpt->description), QByteArray::number(waypt_table->size()).constData());
}
waypt_table->append(wpt);
}
if (global_opts.debug_level >= 1) {
- printf(MYNAME " lowranceusr4_find_waypt: warning, failed finding waypoint with ids %u %d %d\n",
+ gbDebug("lowranceusr4_find_waypt: warning, failed finding waypoint with ids %u %d %d\n",
uid_unit, uid_seq_low, uid_seq_high);
}
return nullptr;
}
if (global_opts.debug_level >= 1) {
- printf(MYNAME " lowranceusr4_find_global_waypt: warning, failed finding waypoint with ids %08x %08x %08x %08x\n",
+ gbDebug("lowranceusr4_find_global_waypt: warning, failed finding waypoint with ids %08x %08x %08x %08x\n",
id1, id2, id3, id4);
}
return nullptr;
void
LowranceusrFormat::rd_init(const QString& fname)
{
- file_in = gbfopen_le(fname, "rb", MYNAME);
+ file_in = gbfopen_le(fname, "rb");
utf16le_codec = QTextCodec::codecForName("UTF-16LE");
}
void
LowranceusrFormat::wr_init(const QString& fname)
{
- file_out = gbfopen_le(fname, "wb", MYNAME);
+ file_out = gbfopen_le(fname, "wb");
mkshort_handle = new MakeShort;
waypt_out_count = 0;
writing_version = opt_wversion.get_result();
if ((writing_version < 2) || (writing_version > 4)) {
- fatal(MYNAME " wversion value %s is not supported !!\n", qPrintable(opt_wversion));
+ gbFatal("wversion value %s is not supported !!\n", gbLogCStr(opt_wversion));
}
utf16le_codec = QTextCodec::codecForName("UTF-16LE");
waypt_table = new QList<const Waypoint*>;
}
void
-LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_present) const
+LowranceusrFormat::lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_present)
{
/* Object num */
if (object_num_present) {
short object_num = gbfgetint16(file_in);
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_waypt: %5d", object_num);
+ gbDebug("parse_waypt: %5d", object_num);
}
}
if (global_opts.debug_level > 1) {
if (global_opts.debug_level == 99) {
if (wpt_tmp->shortname.length() > 16) {
- printf(" %.13s...", qPrintable(wpt_tmp->shortname));
+ gbDebug(" %.13s...", gbLogCStr(wpt_tmp->shortname));
} else {
- printf(" %16.16s", qPrintable(wpt_tmp->shortname));
+ gbDebug(" %16.16s", gbLogCStr(wpt_tmp->shortname));
}
- printf(" %+15.10f %+15.10f", wpt_tmp->latitude, wpt_tmp->longitude);
+ gbDebug(" %+15.10f %+15.10f", wpt_tmp->latitude, wpt_tmp->longitude);
if (wpt_tmp->altitude == unknown_alt) {
- printf(" %13s", "UNKNOWN ALT");
+ gbDebug(" %13s", "UNKNOWN ALT");
} else {
- printf(" %5d %7.1f", (int)METERS_TO_FEET(wpt_tmp->altitude), wpt_tmp->altitude);
+ gbDebug(" %5d %7.1f", (int)METERS_TO_FEET(wpt_tmp->altitude), wpt_tmp->altitude);
}
} else {
- printf(MYNAME " parse_waypt: Waypt name = '%s' Lat = %+f Lon = %+f alt = ",
- qPrintable(wpt_tmp->shortname), wpt_tmp->latitude, wpt_tmp->longitude);
+ gbDebug("parse_waypt: Waypt name = '%s' Lat = %+f Lon = %+f alt = ",
+ gbLogCStr(wpt_tmp->shortname), wpt_tmp->latitude, wpt_tmp->longitude);
if (wpt_tmp->altitude == unknown_alt) {
- printf("UNKNOWN ALT\n");
+ gbDebug("UNKNOWN ALT\n");
} else {
- printf("%d (%f)\n", (int)METERS_TO_FEET(wpt_tmp->altitude), wpt_tmp->altitude);
+ gbDebug("%d (%f)\n", (int)METERS_TO_FEET(wpt_tmp->altitude), wpt_tmp->altitude);
}
}
}
if (global_opts.debug_level > 2) {
if (global_opts.debug_level == 99) {
- printf(" '%s'", qPrintable(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")));
+ gbDebug(" '%s'", gbLogCStr(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")));
} else {
- printf(MYNAME " parse_waypt: creation time '%s', waypt_time %" PRId64 "\n",
- qPrintable(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")), waypt_time);
+ gbDebug("parse_waypt: creation time '%s', waypt_time %" PRId64 "\n",
+ gbLogCStr(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")), waypt_time);
}
}
icon_number = gbfgetint32(file_in);
}
if (global_opts.debug_level == 99) {
- printf(" %08x (%d)", icon_number, icon_number);
+ gbDebug(" %08x (%d)", icon_number, icon_number);
}
wpt_tmp->icon_descr = lowranceusr_find_desc_from_icon_number(icon_number);
short waypt_type = gbfgetint16(file_in);
if (global_opts.debug_level > 2) {
if (global_opts.debug_level == 99) {
- printf(" %04x (%d)", (int)waypt_type, (int)waypt_type);
+ gbDebug(" %04x (%d)", (int)waypt_type, (int)waypt_type);
} else {
- printf(MYNAME " parse_waypt: waypt_type = %d\n",waypt_type);
+ gbDebug("parse_waypt: waypt_type = %d\n",waypt_type);
}
}
if (std::abs(depth_feet - 99999.0) > .1) {
wpt_tmp->set_depth(FEET_TO_METERS(depth_feet));
if (global_opts.debug_level == 99) {
- printf(" %10.1f", depth_feet);
+ gbDebug(" %10.1f", depth_feet);
}
} else {
if (global_opts.debug_level == 99) {
- printf(" UNKNOWN");
+ gbDebug(" UNKNOWN");
}
}
}
if (global_opts.debug_level == 99) {
- printf("\n");
+ gbDebug("\n");
}
}
void
-LowranceusrFormat::lowranceusr4_parse_waypt(Waypoint* wpt_tmp) const
+LowranceusrFormat::lowranceusr4_parse_waypt(Waypoint* wpt_tmp)
{
auto* fsdata = new lowranceusr4_fsdata;
wpt_tmp->fs.FsChainAdd(fsdata);
if (global_opts.debug_level > 1) {
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_waypoints: ");
+ gbDebug("parse_waypoints: ");
if (reading_version > 4) {
- printf("%08x %08x %08x %08x ",
+ gbDebug("%08x %08x %08x %08x ",
fsdata->UUID1, fsdata->UUID2, fsdata->UUID3, fsdata->UUID4);
}
- printf(" %10u %8d %8d %8d %6s",
+ gbDebug(" %10u %8d %8d %8d %6s",
fsdata->uid_unit, fsdata->uid_seq_low, fsdata->uid_seq_high,
waypoint_version, QByteArray::number(name.length()).constData());
if (name.length() > 16) {
- printf(" %13.13s...", qPrintable(name));
+ gbDebug(" %13.13s...", gbLogCStr(name));
} else {
- printf(" %16.16s", qPrintable(name));
+ gbDebug(" %16.16s", gbLogCStr(name));
}
if (reading_version > 4) {
- printf(" %10u ", fsdata->uid_unit2);
+ gbDebug(" %10u ", fsdata->uid_unit2);
}
- printf(" %+15.10f %+15.10f", wpt_tmp->longitude, wpt_tmp->latitude);
- printf(" %08x %4d %4d %7s", fsdata->flags, fsdata->icon_num, fsdata->color,
- (fsdata->color_desc == nullptr ? "unk" : qPrintable(fsdata->color_desc)));
+ gbDebug(" %+15.10f %+15.10f", wpt_tmp->longitude, wpt_tmp->latitude);
+ gbDebug(" %08x %4d %4d %7s", fsdata->flags, fsdata->icon_num, fsdata->color,
+ (fsdata->color_desc == nullptr ? "unk" : gbLogCStr(fsdata->color_desc)));
if (desc.length() > 16) {
- printf(" %6s %.13s...", QByteArray::number(desc.length()).constData(), qPrintable(desc));
+ gbDebug(" %6s %.13s...", QByteArray::number(desc.length()).constData(), gbLogCStr(desc));
} else {
- printf(" %6s %16s", QByteArray::number(desc.length()).constData(), qPrintable(desc));
+ gbDebug(" %6s %16s", QByteArray::number(desc.length()).constData(), gbLogCStr(desc));
}
- printf(" '%s'", qPrintable(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")));
- printf(" %08x %8.3f %08x %08x %08x\n",
+ gbDebug(" '%s'", gbLogCStr(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")));
+ gbDebug(" %08x %8.3f %08x %08x %08x\n",
unused_byte, fsdata->depth, loran_GRI, loran_Tda, loran_Tdb);
} else {
- printf(MYNAME " parse_waypoints: version = %d, name = %s, uid_unit = %u, "
+ gbDebug("parse_waypoints: version = %d, name = %s, uid_unit = %u, "
"uid_seq_low = %d, uid_seq_high = %d, lat = %+.10f, lon = %+.10f, depth = %f\n",
- waypoint_version, qPrintable(wpt_tmp->shortname), fsdata->uid_unit,
+ waypoint_version, gbLogCStr(wpt_tmp->shortname), fsdata->uid_unit,
fsdata->uid_seq_low, fsdata->uid_seq_high,
wpt_tmp->longitude, wpt_tmp->latitude, fsdata->depth);
}
}
void
-LowranceusrFormat::lowranceusr_parse_waypts() const
+LowranceusrFormat::lowranceusr_parse_waypts()
{
int NumWaypoints;
}
if (global_opts.debug_level >= 1) {
- printf(MYNAME " parse_waypts: Num Waypoints = %d\n", NumWaypoints);
+ gbDebug("parse_waypts: Num Waypoints = %d\n", NumWaypoints);
}
if (global_opts.debug_level == 99) {
if (reading_version > 3) {
- printf(MYNAME " parse_waypts: ");
+ gbDebug("parse_waypts: ");
if (reading_version > 4) {
- printf("Universal ID ");
+ gbDebug("Universal ID ");
}
- printf(" Sequence Number Stream Waypoint\n");
+ gbDebug(" Sequence Number Stream Waypoint\n");
- printf(MYNAME " parse_waypoints: ");
+ gbDebug("parse_waypoints: ");
if (reading_version > 4) {
- printf(" ID1 ID2 ID3 ID4 ");
+ gbDebug(" ID1 ID2 ID3 ID4 ");
}
- printf("Unit Number Low High Version Length Name ");
+ gbDebug("Unit Number Low High Version Length Name ");
if (reading_version > 4) {
- printf(" Unit Number2");
+ gbDebug(" Unit Number2");
}
- printf(" Latitude Longitude Flags ICON Color Length Description ");
- printf(" Date Time Unknown Depth LoranGRI LoranTda LoranTdb\n");
+ gbDebug(" Latitude Longitude Flags ICON Color Length Description ");
+ gbDebug(" Date Time Unknown Depth LoranGRI LoranTda LoranTdb\n");
- printf(MYNAME " parse_waypoints: ");
+ gbDebug("parse_waypoints: ");
if (reading_version > 4) {
- printf("-------- -------- -------- -------- ");
+ gbDebug("-------- -------- -------- -------- ");
}
- printf("----------- -------- -------- -------- ------ ----------------");
+ gbDebug("----------- -------- -------- -------- ------ ----------------");
if (reading_version > 4) {
- printf(" ------------");
+ gbDebug(" ------------");
}
- printf(" --------------- --------------- -------- ---- ------------ ------ ----------------");
- printf(" ---------- ----- -------- -------- -------- -------- --------\n");
+ gbDebug(" --------------- --------------- -------- ---- ------------ ------ ----------------");
+ gbDebug(" ---------- ----- -------- -------- -------- -------- --------\n");
} else {
- printf(MYNAME " parse_waypts: Number Name Longitude Latitude Altitude Time ");
- printf(" ICON ID (dec) Flag (dec)");
+ gbDebug("parse_waypts: Number Name Longitude Latitude Altitude Time ");
+ gbDebug(" ICON ID (dec) Flag (dec)");
if (reading_version == 3) {
- printf(" Depth (ft)");
+ gbDebug(" Depth (ft)");
}
- printf("\n");
- printf(MYNAME " parse_waypts: ------ --------------- --------------- -------------- -------------- ----------------");
- printf(" ---------------- ----------");
+ gbDebug("\n");
+ gbDebug("parse_waypts: ------ --------------- --------------- -------------- -------------- ----------------");
+ gbDebug(" ---------------- ----------");
if (reading_version == 3) {
- printf(" ----------");
+ gbDebug(" ----------");
}
- printf("\n");
+ gbDebug("\n");
}
}
lowranceusr4_parse_waypt(wpt_tmp);
break;
default:
- Warning() << MYNAME << ": Unknown internal version " << reading_version;
+ Warning() << "Unknown internal version " << reading_version;
}
waypt_add(wpt_tmp);
}
}
void
-LowranceusrFormat::lowranceusr_parse_route() const
+LowranceusrFormat::lowranceusr_parse_route()
{
/* route name */
QString name = lowranceusr4_readstr(file_in, 1);
short num_legs = gbfgetint16(file_in);
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_route: Route '%s', Num Legs = %d", qPrintable(name), num_legs);
+ gbDebug("parse_route: Route '%s', Num Legs = %d", gbLogCStr(name), num_legs);
}
/* route reversed */
char reversed = gbfgetc(file_in);
if (global_opts.debug_level > 1) {
- printf(", reversed '%x' - %s\n", reversed, (reversed ? "Yes" : "No"));
+ gbDebug(", reversed '%x' - %s\n", reversed, (reversed ? "Yes" : "No"));
}
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_route: Name Longitude Latitude Altitude Time Unknown ICON ID (dec) Flag (dec) Depth (ft)\n");
- printf(MYNAME " parse_route: --------------- --------------- -------------- ------------- ---------------- -------- ---------------- ---------- ----------\n");
+ gbDebug("parse_route: Name Longitude Latitude Altitude Time Unknown ICON ID (dec) Flag (dec) Depth (ft)\n");
+ gbDebug("parse_route: --------------- --------------- -------------- ------------- ---------------- -------- ---------------- ---------- ----------\n");
}
/* waypoints */
for (int j = 0; j < num_legs; j++) {
auto* wpt_tmp = new Waypoint;
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_route:");
+ gbDebug("parse_route:");
}
lowranceusr_parse_waypt(wpt_tmp, 0); /* Indicate object number missing */
route_add_wpt(rte_head, wpt_tmp);
}
void
-LowranceusrFormat::lowranceusr4_parse_route() const
+LowranceusrFormat::lowranceusr4_parse_route()
{
int UUID1 = 0;
int UUID2 = 0;
/* UID unit number */
fsdata->uid_unit = gbfgetint32(file_in);
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_route: Unit %u (0x%08x)\n", fsdata->uid_unit, fsdata->uid_unit);
+ gbDebug("parse_route: Unit %u (0x%08x)\n", fsdata->uid_unit, fsdata->uid_unit);
}
/* 64-bit UID sequence number */
/* Route stream version number */
int route_version = gbfgetint16(file_in);
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_route: Version = %d\n", route_version);
+ gbDebug("parse_route: Version = %d\n", route_version);
}
/* Route name; input is 2 bytes per char, we convert to 1 */
if (global_opts.debug_level > 1) {
if (reading_version >= 5) {
- printf(MYNAME " parse_route: route '%s' (UUID %08x %08x %8x %08x) has %d legs\n",
- qPrintable(rte_head->rte_name), UUID1, UUID2, UUID3, UUID4, num_legs);
+ gbDebug("parse_route: route '%s' (UUID %08x %08x %8x %08x) has %d legs\n",
+ gbLogCStr(rte_head->rte_name), UUID1, UUID2, UUID3, UUID4, num_legs);
} else {
- printf(MYNAME " parse_route: route '%s' has %d legs\n",
- qPrintable(rte_head->rte_name), num_legs);
+ gbDebug("parse_route: route '%s' has %d legs\n",
+ gbLogCStr(rte_head->rte_name), num_legs);
}
}
const Waypoint* wpt_tmp = lowranceusr4_find_waypt(uid_unit, uid_seq_low, uid_seq_high);
if (wpt_tmp) {
if (global_opts.debug_level >= 2) {
- printf(MYNAME " parse_route: added leg #%d routepoint %s (%+.10f, %+.10f)\n",
- j, qPrintable(wpt_tmp->shortname), wpt_tmp->longitude, wpt_tmp->latitude);
+ gbDebug("parse_route: added leg #%d routepoint %s (%+.10f, %+.10f)\n",
+ j, gbLogCStr(wpt_tmp->shortname), wpt_tmp->longitude, wpt_tmp->latitude);
}
route_add_wpt(rte_head, new Waypoint(*wpt_tmp));
}
const Waypoint* wpt_tmp = lowranceusr4_find_global_waypt(UUID1, UUID2, UUID3, UUID4);
if (wpt_tmp) {
if (global_opts.debug_level >= 2) {
- printf(MYNAME " parse_route: added leg #%d routepoint %s (%+.10f, %+.10f)\n",
- j, qPrintable(wpt_tmp->shortname), wpt_tmp->longitude, wpt_tmp->latitude);
+ gbDebug("parse_route: added leg #%d routepoint %s (%+.10f, %+.10f)\n",
+ j, gbLogCStr(wpt_tmp->shortname), wpt_tmp->longitude, wpt_tmp->latitude);
}
route_add_wpt(rte_head, new Waypoint(*wpt_tmp));
}
/* Mystery byte, discard */
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_route: end of route %02x\n", gbfgetc(file_in));
+ gbDebug("parse_route: end of route %02x\n", gbfgetc(file_in));
} else {
gbfgetc(file_in);
}
}
if (global_opts.debug_level >= 1) {
- printf(MYNAME " parse_routes: Num Routes = %d\n", num_routes);
+ gbDebug("parse_routes: Num Routes = %d\n", num_routes);
}
for (int i = 0; i < num_routes; i++) {
* option of ignoreicons is used
*/
void
-LowranceusrFormat::lowranceusr_parse_icons() const
+LowranceusrFormat::lowranceusr_parse_icons()
{
short int num_icons = gbfgetint16(file_in);
if (global_opts.debug_level >= 1) {
- printf(MYNAME " parse_icons: Num Event Marker Icons = %d\n", num_icons);
+ gbDebug("parse_icons: Num Event Marker Icons = %d\n", num_icons);
}
for (int i = 0; i < num_icons && !gbfeof(file_in); i++) {
wpt_tmp->icon_descr = lowranceusr_find_desc_from_icon_number(icon_number);
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_icons: '%s' %d %16.16s %+15.10f %+15.10f\n",
- qPrintable(wpt_tmp->shortname), icon_number, qPrintable(wpt_tmp->icon_descr), wpt_tmp->latitude, wpt_tmp->longitude);
+ gbDebug("parse_icons: '%s' %d %16.16s %+15.10f %+15.10f\n",
+ gbLogCStr(wpt_tmp->shortname), icon_number, gbLogCStr(wpt_tmp->icon_descr), wpt_tmp->latitude, wpt_tmp->longitude);
}
waypt_add(wpt_tmp);
}
}
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_trails: Trail '%s'\n", qPrintable(trk_head->rte_name));
+ gbDebug("parse_trails: Trail '%s'\n", gbLogCStr(trk_head->rte_name));
}
/* visible */
char visible = gbfgetc(file_in);
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_trails: Visible '%x' - %s\n", visible, (visible ? "Yes" : "No"));
+ gbDebug("parse_trails: Visible '%x' - %s\n", visible, (visible ? "Yes" : "No"));
}
/* num trail points */
short num_trail_points = gbfgetint16(file_in);
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_trails: Num Trail Points = %d\n", num_trail_points);
+ gbDebug("parse_trails: Num Trail Points = %d\n", num_trail_points);
}
/* max trail size */
int itmp = gbfgetint16(file_in);
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_trails: Max Trail size = %d\n", itmp);
+ gbDebug("parse_trails: Max Trail size = %d\n", itmp);
}
if (num_trail_points) {
num_section_points = gbfgetint16(file_in);
if (global_opts.debug_level > 1) {
- printf(MYNAME " parse_trails: Num Section Points = %d\n", num_section_points);
+ gbDebug("parse_trails: Num Section Points = %d\n", num_section_points);
}
for (int j = 0; j < num_section_points && !gbfeof(file_in); j++, num_trail_points--) {
track_add_wpt(trk_head, wpt_tmp);
if (global_opts.debug_level > 2) {
- printf(MYNAME " parse_trails: Trail pt lat %f lon %f\n", wpt_tmp->latitude, wpt_tmp->longitude);
+ gbDebug("parse_trails: Trail pt lat %f lon %f\n", wpt_tmp->latitude, wpt_tmp->longitude);
}
}
}
}
void
-LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num) const
+LowranceusrFormat::lowranceusr4_parse_trail(int* trail_num)
{
auto* fsdata = new lowranceusr4_fsdata;
trk_head->fs.FsChainAdd(fsdata);
/* Trail stream version number */
int trail_version = gbfgetint16(file_in);
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_trails: trail Version %d\n", trail_version);
+ gbDebug("parse_trails: trail Version %d\n", trail_version);
}
if ((trail_version < 3) || (trail_version > 5)) {
- fatal(MYNAME " trail version %d not supported!!", trail_version);
+ gbFatal("trail version %d not supported!!\n", trail_version);
}
/* Trail name; input is 2 bytes per char, we convert to 1 */
trk_head->rte_name = name;
}
if (global_opts.debug_level >= 2) {
- printf(MYNAME " parse_trails: Trail '%s'\n", qPrintable(trk_head->rte_name));
+ gbDebug("parse_trails: Trail '%s'\n", gbLogCStr(trk_head->rte_name));
}
/* Flags, discard for now */
trk_head->rte_desc = desc;
}
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_trails: Comment '%s'\n", qPrintable(desc));
+ gbDebug("parse_trails: Comment '%s'\n", gbLogCStr(desc));
}
/* Creation date/time, discard for now */
int create_time = gbfgetint32(file_in);
if (global_opts.debug_level == 99) {
QDateTime qdt = lowranceusr4_get_timestamp(create_date, create_time);
- printf(MYNAME " parse_trails: creation date/time = %s\n", qPrintable(qdt.toString(u"yyyy-MM-dd hh:mm:ss AP")));
+ gbDebug("parse_trails: creation date/time = %s\n", gbLogCStr(qdt.toString(u"yyyy-MM-dd hh:mm:ss AP")));
}
/* Some flag bytes */
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_trails: unknown flag bytes %02x %02x %02x\n",
+ gbDebug("parse_trails: unknown flag bytes %02x %02x %02x\n",
gbfgetc(file_in), gbfgetc(file_in), gbfgetc(file_in));
} else {
/* just discard */
/* Mysterious attribute "data count" */
int attr_count = gbfgetint32(file_in);
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_trails: attribute count %4d : (", attr_count);
+ gbDebug("parse_trails: attribute count %4d : (", attr_count);
for (int i=0; i<attr_count; i++) {
if (trail_version == 5) {
- printf("%08x ", gbfgetint32(file_in));
+ gbDebug("%08x ", gbfgetint32(file_in));
} else {
- printf("%02x ", gbfgetc(file_in));
+ gbDebug("%02x ", gbfgetc(file_in));
}
}
- printf(")\n");
+ gbDebug(")\n");
} else {
/* just discard */
for (int i=0; i<attr_count; i++) {
int num_trail_pts = gbfgetint32(file_in);
if (global_opts.debug_level >= 2) {
- printf(MYNAME " parse_trails: trail %d name='%s' color=%d flags=%d has %d (%x) trailpoints\n",
- *trail_num, qPrintable(trk_head->rte_name), trail_color, trail_flags, num_trail_pts, num_trail_pts);
+ gbDebug("parse_trails: trail %d name='%s' color=%d flags=%d has %d (%x) trailpoints\n",
+ *trail_num, gbLogCStr(trk_head->rte_name), trail_color, trail_flags, num_trail_pts, num_trail_pts);
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_trails: Longitude Latitude Flag/Value pairs (01=Speed)\n");
- printf(MYNAME " parse_trails: -------------- -------------- -- -------- -- -------- -- --------\n");
+ gbDebug("parse_trails: Longitude Latitude Flag/Value pairs (01=Speed)\n");
+ gbDebug("parse_trails: -------------- -------------- -- -------- -- -------- -- --------\n");
}
}
for (int j = 0; j < num_trail_pts; ++j) {
if (global_opts.debug_level >= 2) {
if (global_opts.debug_level == 99) {
- printf(MYNAME " parse_trails: %+14.9f %+14.9f", wpt_tmp->longitude, wpt_tmp->latitude);
- printf(" '%s'", qPrintable(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")));
+ gbDebug("parse_trails: %+14.9f %+14.9f", wpt_tmp->longitude, wpt_tmp->latitude);
+ gbDebug(" '%s'", gbLogCStr(wpt_tmp->GetCreationTime().toString(u"yyyy/MM/dd hh:mm:ss")));
} else {
- printf(MYNAME " parse_trails: added trailpoint %+.9f,%+.9f to trail %s\n",
- wpt_tmp->longitude, wpt_tmp->latitude, qPrintable(trk_head->rte_name));
+ gbDebug("parse_trails: added trailpoint %+.9f,%+.9f to trail %s\n",
+ wpt_tmp->longitude, wpt_tmp->latitude, gbLogCStr(trk_head->rte_name));
}
}
int flag = gbfgetc(file_in);
float value = gbfgetflt(file_in);
if (global_opts.debug_level == 99) {
- printf(" %02x %f", flag, value);
+ gbDebug(" %02x %f", flag, value);
}
}
if (global_opts.debug_level == 99) {
- printf("\n");
+ gbDebug("\n");
}
}
}
}
if (global_opts.debug_level >= 1) {
- printf(MYNAME " parse_trails: Num Trails = %d\n", num_trails);
+ gbDebug("parse_trails: Num Trails = %d\n", num_trails);
}
for (int i = trail_num = 0; i < num_trails && !gbfeof(file_in); i++) {
reading_version = gbfgetint16(file_in);
rstream_version = gbfgetint16(file_in);
if (global_opts.debug_level >= 1) {
- printf(MYNAME " input_file: USR File Format %d (Version = %d)\n", reading_version, rstream_version);
+ gbDebug("input_file: USR File Format %d (Version = %d)\n", reading_version, rstream_version);
}
if ((reading_version < 2) || (reading_version > 6)) {
- fatal(MYNAME " input file is a USR format that is not supported\n");
+ gbFatal("input file is a USR format that is not supported\n");
}
if (reading_version >= 4) {
/* Starting with USR version 4 have an unknown here */
int unknown = gbfgetint32(file_in);
if (global_opts.debug_level >= 1) {
- printf(MYNAME " input_file: Unknown %d (%x)\n", unknown, unknown);
+ gbDebug("input_file: Unknown %d (%x)\n", unknown, unknown);
}
/* USR files also now contain a file title */
QString title = lowranceusr4_readstr(file_in, 1);
if (!title.isEmpty() && global_opts.debug_level >= 1) {
- printf(MYNAME " file title: '%s'\n", qPrintable(title));
+ gbDebug("file title: '%s'\n", gbLogCStr(title));
}
/* AND a date created string */
QString creation_date = lowranceusr4_readstr(file_in, 1);
if (!creation_date.isEmpty() && global_opts.debug_level >= 1) {
- printf(MYNAME " date string: '%s'\n", qPrintable(creation_date));
+ gbDebug("date string: '%s'\n", gbLogCStr(creation_date));
}
/* Creation date/time, discard for now */
int create_time = gbfgetint32(file_in);
if (global_opts.debug_level >= 1) {
QDateTime qdt = lowranceusr4_get_timestamp(create_date, create_time);
- printf(MYNAME " creation date/time : '%s'\n", qPrintable(qdt.toString(u"yyyy-MM-dd hh:mm:ss AP")));
+ gbDebug("creation date/time : '%s'\n", gbLogCStr(qdt.toString(u"yyyy-MM-dd hh:mm:ss AP")));
}
unsigned char byte = gbfgetc(file_in); /* unused, apparently */
/* AND the serial number of the unit that created the file */
uint serial_num = gbfgetint32(file_in);
if (global_opts.debug_level >= 1) {
- printf(MYNAME " device serial number: %u\n", serial_num);
+ gbDebug("device serial number: %u\n", serial_num);
}
/* AND a comment on the file contents */
QString comment = lowranceusr4_readstr(file_in, 1);
if (!comment.isEmpty() && global_opts.debug_level >= 1) {
- printf(MYNAME " content description: '%s'\n", qPrintable(comment));
+ gbDebug("content description: '%s'\n", gbLogCStr(comment));
}
}
}
void
-LowranceusrFormat::lowranceusr_waypt_disp(const Waypoint* wpt) const
+LowranceusrFormat::lowranceusr_waypt_disp(const Waypoint* wpt)
{
int SymbolId;
int alt;
if (global_opts.debug_level > 2) {
/* print lat/lon/alt on one easily greppable line */
- printf(MYNAME " waypt_disp: Waypt name = '%s' Lat = %+16.10f Lon = %+16.10f Alt = %f\n",
- qPrintable(wpt->shortname), wpt->latitude, wpt->longitude, wpt->altitude);
+ gbDebug("waypt_disp: Waypt name = '%s' Lat = %+16.10f Lon = %+16.10f Alt = %f\n",
+ gbLogCStr(wpt->shortname), wpt->latitude, wpt->longitude, wpt->altitude);
}
QByteArray name_qba = name.toLatin1();
gbfwrite(name_qba.constData(), 1, text_len, file_out);
if (global_opts.debug_level > 1) {
- printf(MYNAME " waypt_disp: Waypt name = '%s' ", qPrintable(name));
+ gbDebug("waypt_disp: Waypt name = '%s' ", gbLogCStr(name));
}
/**
/* Lowrance needs it as seconds since Jan 1, 2000 */
waypt_time -= base_time_secs;
if (global_opts.debug_level >= 2) {
- printf("creation_time %" PRId64 ", '%s'", waypt_time, qPrintable(wpt->GetCreationTime().toString(u"yyyy-MM-dd hh:mm:ss")));
+ gbDebug("creation_time %" PRId64 ", '%s'", waypt_time, gbLogCStr(wpt->GetCreationTime().toString(u"yyyy-MM-dd hh:mm:ss")));
}
} else {
/* If false, make sure it is an unknown time value */
waypt_time = 0;
if (global_opts.debug_level >= 2) {
- printf("creation_time UNKNOWN");
+ gbDebug("creation_time UNKNOWN");
}
}
}
if (global_opts.debug_level > 1) {
- printf("\n");
+ gbDebug("\n");
}
}
gbfputint16(waypt_out_count, file_out);
if (global_opts.debug_level >= 3) {
- printf(MYNAME " waypt_pr: waypoint #%d\n",waypt_out_count);
+ gbDebug("waypt_pr: waypoint #%d\n",waypt_out_count);
}
waypt_out_count++;
route_disp_all(nullptr, nullptr, register_waypt_lambda);
if (global_opts.debug_level >= 1) {
- printf(MYNAME " writing %s waypoints\n", QByteArray::number(waypt_table->size()).constData());
+ gbDebug("writing %s waypoints\n", QByteArray::number(waypt_table->size()).constData());
}
gbfputint32(waypt_table->size(), file_out);
waypt_uid = 0;
for (int i = 0; i < waypt_table->size(); ++i) {
if (global_opts.debug_level >= 2) {
- printf(MYNAME " writing out waypt %d (%s - %s)\n",
- i, qPrintable(waypt_table->at(i)->shortname), qPrintable(waypt_table->at(i)->description));
+ gbDebug("writing out waypt %d (%s - %s)\n",
+ i, gbLogCStr(waypt_table->at(i)->shortname), gbLogCStr(waypt_table->at(i)->description));
}
lowranceusr4_waypt_disp((waypt_table->at(i)));
}
* 4 bytes symbol
*/
void
-LowranceusrFormat::lowranceusr_write_icon(const Waypoint* wpt) const
+LowranceusrFormat::lowranceusr_write_icon(const Waypoint* wpt)
{
int latmm = lat_deg_to_mm(wpt->latitude);
int lonmm = lon_deg_to_mm(wpt->longitude);
text_len = MAXUSRSTRINGSIZE;
}
if (global_opts.debug_level >= 1) {
- printf(MYNAME " trail_hdr: trail name '%s' ", qPrintable(trk->rte_name));
+ gbDebug("trail_hdr: trail name '%s' ", gbLogCStr(trk->rte_name));
}
gbfputint32(text_len, file_out);
gbfwrite(CSTR(name), 1, text_len, file_out);
num_section_points = num_trail_points;
if (global_opts.debug_level) {
- printf("num_trail_points = %d ", num_trail_points);
+ gbDebug("num_trail_points = %d ", num_trail_points);
if (global_opts.debug_level > 1) {
- printf("max_trail_size = %d num_section_points = %d\n", max_trail_size, num_section_points);
+ gbDebug("max_trail_size = %d num_section_points = %d\n", max_trail_size, num_section_points);
} else {
- printf("\n");
+ gbDebug("\n");
}
}
gbfwrite(&route_reversed, 1, 1, file_out);
if (global_opts.debug_level >= 1)
- printf(MYNAME " route_hdr: route name \"%s\" num_legs = %d\n",
- qPrintable(rte->rte_name), num_legs);
+ gbDebug("route_hdr: route name \"%s\" num_legs = %d\n",
+ gbLogCStr(rte->rte_name), num_legs);
}
void
LowranceusrFormat::lowranceusr4_route_hdr(const route_head* rte)
{
if (global_opts.debug_level >= 1) {
- printf(MYNAME " writing route #%d (%s) with %d waypts\n",
- route_uid, qPrintable(rte->rte_name), rte->rte_waypt_ct());
+ gbDebug("writing route #%d (%s) with %d waypts\n",
+ route_uid, gbLogCStr(rte->rte_name), rte->rte_waypt_ct());
}
const auto* fs = reinterpret_cast<lowranceusr4_fsdata*>(rte->fs.FsChainFind(kFsLowranceusr4));
}
void
-LowranceusrFormat::lowranceusr4_route_leg_disp(const Waypoint* wpt) const
+LowranceusrFormat::lowranceusr4_route_leg_disp(const Waypoint* wpt)
{
for (int i = 0; i < waypt_table->size(); i++) {
const Waypoint* cmp = waypt_table->at(i);
gbfputint32(i, file_out); // Sequence Low
gbfputint32(0, file_out); // Sequence High
if (global_opts.debug_level > 1) {
- printf(MYNAME " wrote route leg with waypt '%s'\n", qPrintable(wpt->shortname));
+ gbDebug("wrote route leg with waypt '%s'\n", gbLogCStr(wpt->shortname));
}
break;
}
}
void
-LowranceusrFormat::lowranceusr4_route_trl(const route_head* /*unused*/) const
+LowranceusrFormat::lowranceusr4_route_trl(const route_head* /*unused*/)
{
/* Mystery byte */
gbfputc(0x01, file_out); // end of Route info ??
int lon = lon_deg_to_mm(wpt->longitude);
if (global_opts.debug_level > 1) {
- printf(MYNAME " trail_disp: Trail point #%d lat = %f long = %f\n",trail_point_count, wpt->latitude, wpt->longitude);
+ gbDebug("trail_disp: Trail point #%d lat = %f long = %f\n",trail_point_count, wpt->latitude, wpt->longitude);
}
gbfputint32(lat, file_out);
gbfputs(name, file_out);
if (global_opts.debug_level >= 1) {
- printf(MYNAME " trail_hdr: trail name = %s\n", CSTR(name));
+ gbDebug("trail_hdr: trail name = %s\n", CSTR(name));
}
}
num_section_points = num_trail_points;
if (global_opts.debug_level >= 1)
- printf(MYNAME " merge_trail_tlr: num_trail_points = %d\nmax_trail_size = %d\nnum_section_points = %d\n",
+ gbDebug("merge_trail_tlr: num_trail_points = %d\nmax_trail_size = %d\nnum_section_points = %d\n",
num_trail_points, max_trail_size, num_section_points);
const char visible=1;
LowranceusrFormat::lowranceusr4_trail_hdr(const route_head* trail)
{
if (global_opts.debug_level >= 1) {
- printf(MYNAME " writing trail %d (%s) with %d trailpoints\n",
- trail_uid, qPrintable(trail->rte_name), trail->rte_waypt_ct());
+ gbDebug("writing trail %d (%s) with %d trailpoints\n",
+ trail_uid, gbLogCStr(trail->rte_name), trail->rte_waypt_ct());
}
/* UID unit number */
}
void
-LowranceusrFormat::lowranceusr4_trail_disp(const Waypoint* wpt) const
+LowranceusrFormat::lowranceusr4_trail_disp(const Waypoint* wpt)
{
/* Some unknown bytes */
gbfputint16(0, file_out);
int NumWaypoints = waypt_count();
if (global_opts.debug_level >= 1) {
- printf(MYNAME " data_write: Num Waypoints = %d\n", NumWaypoints);
+ gbDebug("data_write: Num Waypoints = %d\n", NumWaypoints);
}
// If writeasicons option specified then all Waypoints processed are written as
buf = opt_title.isEmpty()?
QStringLiteral("GPSBabel generated USR data file") : opt_title;
if (global_opts.debug_level >= 1) {
- printf(MYNAME " data_write: Title = '%s'\n", qPrintable(buf));
+ gbDebug("data_write: Title = '%s'\n", gbLogCStr(buf));
}
lowranceusr4_writestr(buf, file_out, 1);
buf = opt_content_descr.isEmpty()?
QStringLiteral("Waypoints, routes, and trails") : opt_content_descr;
if (global_opts.debug_level >= 1) {
- printf(MYNAME " data_write: Description = '%s'\n", qPrintable(buf));
+ gbDebug("data_write: Description = '%s'\n", gbLogCStr(buf));
}
lowranceusr4_writestr(buf, file_out, 1);
lowrance_route_count=0;
if (global_opts.debug_level >= 1) {
- printf(MYNAME " data_write: Num routes = %d\n", NumRoutes);
+ gbDebug("data_write: Num routes = %d\n", NumRoutes);
}
if ((writing_version == 2) || (writing_version == 3)) {
track_disp_all(lowranceusr_merge_trail_hdr_2_lambda, nullptr, lowranceusr_trail_disp_lambda);
} else {
/* MERGE NEEDS SOME MORE WORK */
- fatal(MYNAME " output file USR %d format is not supported with merge option\n", writing_version);
+ gbFatal("output file USR %d format is not supported with merge option\n", writing_version);
}
} else {
if (global_opts.debug_level >= 1) {
- printf(MYNAME " data_write: Num trails = %d\n", NumTrails);
+ gbDebug("data_write: Num trails = %d\n", NumTrails);
}
if ((writing_version == 2) || (writing_version == 3)) {
// USR version 2 & 3 use 16-bit count
/* Member Functions */
static bool same_points(const Waypoint* A, const Waypoint* B);
- void register_waypt(const Waypoint* wpt) const;
+ void register_waypt(const Waypoint* wpt);
static const Waypoint* lowranceusr4_find_waypt(uint uid_unit, int uid_seq_low, int uid_seq_high);
static const Waypoint* lowranceusr4_find_global_waypt(uint id1, uint id2, uint id3, uint id4);
QString lowranceusr4_readstr(gbfile* file, int bytes_per_char) const;
static double lat_mm_to_deg(double x);
static long int lon_deg_to_mm(double x);
static long int lat_deg_to_mm(double x);
- void lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_present) const;
- void lowranceusr4_parse_waypt(Waypoint* wpt_tmp) const;
- void lowranceusr_parse_waypts() const;
- void lowranceusr_parse_route() const;
- void lowranceusr4_parse_route() const;
+ void lowranceusr_parse_waypt(Waypoint* wpt_tmp, int object_num_present);
+ void lowranceusr4_parse_waypt(Waypoint* wpt_tmp);
+ void lowranceusr_parse_waypts();
+ void lowranceusr_parse_route();
+ void lowranceusr4_parse_route();
void lowranceusr_parse_routes();
- void lowranceusr_parse_icons() const;
+ void lowranceusr_parse_icons();
void lowranceusr_parse_trail(int* trail_num);
- void lowranceusr4_parse_trail(int* trail_num) const;
+ void lowranceusr4_parse_trail(int* trail_num);
void lowranceusr_parse_trails();
- void lowranceusr_waypt_disp(const Waypoint* wpt) const;
+ void lowranceusr_waypt_disp(const Waypoint* wpt);
void lowranceusr4_waypt_disp(const Waypoint* wpt);
void lowranceusr_waypt_pr(const Waypoint* wpt);
void lowranceusr4_write_waypoints();
- void lowranceusr_write_icon(const Waypoint* wpt) const;
+ void lowranceusr_write_icon(const Waypoint* wpt);
void lowranceusr_trail_hdr(const route_head* trk);
void lowranceusr_route_hdr(const route_head* rte);
void lowranceusr4_route_hdr(const route_head* rte);
- void lowranceusr4_route_leg_disp(const Waypoint* wpt) const;
- void lowranceusr4_route_trl(const route_head* /*unused*/) const;
+ void lowranceusr4_route_leg_disp(const Waypoint* wpt);
+ void lowranceusr4_route_trl(const route_head* /*unused*/);
void lowranceusr_trail_disp(const Waypoint* wpt);
void lowranceusr_merge_trail_hdr(const route_head* trk);
void lowranceusr_merge_trail_tlr(const route_head* /*unused*/);
void lowranceusr_merge_trail_hdr_2(const route_head* /*unused*/);
void lowranceusr4_trail_hdr(const route_head* trail);
- void lowranceusr4_trail_disp(const Waypoint* wpt) const;
+ void lowranceusr4_trail_disp(const Waypoint* wpt);
/* Data Members */
#include <cstring> // for strcmp
#include <QCoreApplication> // for QCoreApplication
+#include <QDateTime> // for QDateTime
+#include <QDebug> // for QDebug
#include <QElapsedTimer> // for QElapsedTimer
#include <QFile> // for QFile
#include <QIODevice> // for QIODevice::ReadOnly
static constexpr bool DEBUG_LOCALE = false;
-#define MYNAME "main"
// be careful not to advance argn passed the end of the list, i.e. ensure argn < qargs.size()
#define FETCH_OPTARG qargs.at(argn).size() > 2 ? QString(qargs.at(argn)).remove(0,2) : qargs.size()>(argn+1) ? qargs.at(++argn) : QString()
"\n");
}
-static void MessageHandler(QtMsgType /* type */, const QMessageLogContext& /* context */, const QString& msg)
+static void setMessagePattern(const QString& id = QString())
{
- /* flush any buffered standard output */
- fflush(stdout);
- fprintf(stderr, "%s\n", qPrintable(msg));
+ if (id.isEmpty()) {
+ qSetMessagePattern("%{if-category}%{category}: %{endif}main: %{message}");
+ } else {
+ qSetMessagePattern(QStringLiteral("%{if-category}%{category}: %{endif}%1: %{message}").arg(id));
+ }
}
static void
timer.start();
}
start_session(ivecs.fmtname, fname);
+ setMessagePattern(ivecs.fmtname);
if (ivecs.isDynamic()) {
ivecs.fmt = ivecs.factory(fname);
Vecs::init_vec(ivecs.fmt, ivecs.fmtname);
ivecs->read();
ivecs->rd_deinit();
}
+ setMessagePattern();
if (global_opts.debug_level > 0) {
- Warning().noquote() << QStringLiteral("%1: reader %2 took %3 seconds.")
- .arg(MYNAME, ivecs.fmtname, QString::number(timer.elapsed()/1000.0, 'f', 3));
+ qDebug().noquote() << QStringLiteral("reader %1 took %2 seconds.")
+ .arg(ivecs.fmtname, QString::number(timer.elapsed()/1000.0, 'f', 3));
}
}
if (global_opts.debug_level > 0) {
timer.start();
}
+ setMessagePattern(ovecs.fmtname);
if (ovecs.isDynamic()) {
ovecs.fmt = ovecs.factory(ofname);
Vecs::init_vec(ovecs.fmt, ovecs.fmtname);
ovecs->write();
ovecs->wr_deinit();
}
+ setMessagePattern();
if (global_opts.debug_level > 0) {
- Warning().noquote() << QStringLiteral("%1: writer %2 took %3 seconds.")
- .arg(MYNAME, ovecs.fmtname, QString::number(timer.elapsed()/1000.0, 'f', 3));
+ qDebug().noquote() << QStringLiteral("writer %1 took %2 seconds.")
+ .arg(ovecs.fmtname, QString::number(timer.elapsed()/1000.0, 'f', 3));
}
}
argument = FETCH_OPTARG;
ivecs = Vecs::Instance().find_vec(argument);
if (!ivecs) {
- fatal("Input type '%s' not recognized\n", qPrintable(argument));
+ gbFatal("Input type '%s' not recognized\n", gbLogCStr(argument));
}
break;
case 'o':
if (!ivecs) {
- warning("-o appeared before -i. This is probably not what you want to do.\n");
+ gbWarning("-o appeared before -i. This is probably not what you want to do.\n");
}
argument = FETCH_OPTARG;
ovecs = Vecs::Instance().find_vec(argument);
if (!ovecs) {
- fatal("Output type '%s' not recognized\n", qPrintable(argument));
+ gbFatal("Output type '%s' not recognized\n", gbLogCStr(argument));
}
break;
case 'f':
argument = FETCH_OPTARG;
fname = argument;
if (fname.isEmpty()) {
- fatal("No file or device name specified.\n");
+ gbFatal("No file or device name specified.\n");
}
if (!ivecs) {
- fatal("No valid input type specified\n");
+ gbFatal("No valid input type specified\n");
}
if (global_opts.masked_objective & POSNDATAMASK) {
did_something = true;
argument = FETCH_OPTARG;
ofname = argument;
if (ofname.isEmpty()) {
- fatal("No output file or device name specified.\n");
+ gbFatal("No output file or device name specified.\n");
}
if (ovecs && (!(global_opts.masked_objective & POSNDATAMASK))) {
/* simulates the default behaviour of waypoints */
if (global_opts.debug_level > 0) {
timer.start();
}
+ setMessagePattern(filter.fltname);
if (filter.isDynamic()) {
filter.flt = filter.factory();
FilterVecs::init_filter_vec(filter.flt, filter.fltname);
filter->deinit();
FilterVecs::free_filter_vec(filter.flt);
}
+ setMessagePattern();
if (global_opts.debug_level > 0) {
- Warning().noquote() << QStringLiteral("%1: filter %2 took %3 seconds.")
- .arg(MYNAME, filter.fltname, QString::number(timer.elapsed()/1000.0, 'f', 3));
+ qDebug().noquote() << QStringLiteral("filter %1 took %2 seconds.")
+ .arg(filter.fltname, QString::number(timer.elapsed()/1000.0, 'f', 3));
}
} else {
- fatal("Unknown filter '%s'\n",qPrintable(argument));
+ gbFatal("Unknown filter '%s'\n",gbLogCStr(argument));
}
break;
case 'D':
bool ok;
global_opts.debug_level = argument.toInt(&ok);
if (!ok) {
- fatal("the -D option requires an integer value to specify the debug level, i.e. -D level\n");
+ gbFatal("the -D option requires an integer value to specify the debug level, i.e. -D level\n");
}
}
/*
* When debugging, announce version.
*/
if (global_opts.debug_level > 0) {
- warning("GPSBabel Version: %s\n", gpsbabel_version);
+ gbInfo("GPSBabel Version: %s\n", gpsbabel_version);
if(sizeof(kVersionSHA) > 1) {
- warning(MYNAME ": Repository SHA: %s\n", kVersionSHA);
+ gbInfo("Repository SHA: %s\n", kVersionSHA);
}
if(sizeof(kVersionDate) > 1) {
QDateTime date = QDateTime::fromString(kVersionDate, Qt::ISODate);
if (date.isValid()) {
- warning(MYNAME ": Date: %s\n", qPrintable(date.toUTC().toString(Qt::ISODate)));
+ gbInfo("Date: %s\n", gbLogCStr(date.toUTC().toString(Qt::ISODate)));
}
}
- warning(MYNAME ": Compiled with Qt %s for architecture %s\n",
+ gbInfo("Compiled with Qt %s for architecture %s\n",
QT_VERSION_STR,
- qPrintable(QSysInfo::buildAbi()));
- warning(MYNAME ": Running with Qt %s on %s, %s\n", qVersion(),
- qPrintable(QSysInfo::prettyProductName()),
- qPrintable(QSysInfo::currentCpuArchitecture()));
- warning(MYNAME ": QLocale::system() is %s\n", qPrintable(QLocale::system().name()));
- warning(MYNAME ": QLocale() is %s\n", qPrintable(QLocale().name()));
+ gbLogCStr(QSysInfo::buildAbi()));
+ gbInfo("Running with Qt %s on %s, %s\n", qVersion(),
+ gbLogCStr(QSysInfo::prettyProductName()),
+ gbLogCStr(QSysInfo::currentCpuArchitecture()));
+ gbInfo("QLocale::system() is %s\n", gbLogCStr(QLocale::system().name()));
+ gbInfo("QLocale() is %s\n", gbLogCStr(QLocale().name()));
QTextCodec* defaultcodec = QTextCodec::codecForLocale();
- warning(MYNAME ": QTextCodec::codecForLocale() is %s, mib %d\n",
+ gbInfo("QTextCodec::codecForLocale() is %s, mib %d\n",
defaultcodec->name().constData(),defaultcodec->mibEnum());
}
break;
if (argument.isEmpty()) { /* from GUI to preserve inconsistent options */
global_opts.inifile = nullptr;
} else {
- global_opts.inifile = inifile_init(argument, MYNAME);
+ global_opts.inifile = inifile_init(argument);
}
break;
case 'b':
break;
default:
- fatal("Unknown option '%s'.\n", qPrintable(qargs.at(argn)));
+ gbFatal("Unknown option '%s'.\n", gbLogCStr(qargs.at(argn)));
break;
}
qargs.removeFirst();
}
if (qargs.size() > 2) {
- fatal("Extra arguments on command line\n");
+ gbFatal("Extra arguments on command line\n");
} else if ((!qargs.isEmpty()) && ivecs) {
did_something = true;
/* simulates the default behaviour of waypoints */
if (global_opts.masked_objective & POSNDATAMASK) {
if (!ivecs) {
- fatal("Realtime tracking (-T) requires an input type (-t)i such as Garmin or NMEA.\n");
+ gbFatal("Realtime tracking (-T) requires an input type (-t)i such as Garmin or NMEA.\n");
}
if (fname.isEmpty()) {
- fatal("An input file (-f) must be specified.\n");
+ gbFatal("An input file (-f) must be specified.\n");
}
if (ivecs.isDynamic()) {
+ setMessagePattern(ivecs.fmtname);
ivecs.fmt = ivecs.factory(fname);
Vecs::init_vec(ivecs.fmt, ivecs.fmtname);
+ setMessagePattern();
}
if (ovecs && ovecs.isDynamic()) {
+ setMessagePattern(ovecs.fmtname);
ovecs.fmt = ovecs.factory(ofname);
Vecs::init_vec(ovecs.fmt, ovecs.fmtname);
+ setMessagePattern();
}
start_session(ivecs.fmtname, fname);
+ setMessagePattern(ivecs.fmtname);
Vecs::prepare_format(ivecs);
ivecs->rd_position_init(fname);
+ setMessagePattern();
if (global_opts.masked_objective & ~POSNDATAMASK) {
- fatal("Realtime tracking (-T) is exclusive of other modes.\n");
+ gbFatal("Realtime tracking (-T) is exclusive of other modes.\n");
}
if (signal(SIGINT, signal_handler) == SIG_ERR) {
- fatal("Couldn't install the exit signal handler.\n");
+ gbFatal("Couldn't install the exit signal handler.\n");
}
if (ovecs) {
+ setMessagePattern(ovecs.fmtname);
Vecs::prepare_format(ovecs);
ovecs->wr_position_init(ofname);
+ setMessagePattern();
}
tracking_status.request_terminate = 0;
while (!tracking_status.request_terminate) {
+ setMessagePattern(ivecs.fmtname);
Waypoint* wpt = ivecs->rd_position(&tracking_status);
+ setMessagePattern();
if (tracking_status.request_terminate) {
delete wpt;
break;
}
if (wpt) {
+ setMessagePattern(ovecs.fmtname);
if (ovecs) {
// ovecs->wr_position_init(ofname);
ovecs->wr_position(wpt);
fbOutput.waypt_disp(wpt);
}
delete wpt;
+ setMessagePattern();
}
}
+ setMessagePattern(ivecs.fmtname);
Vecs::prepare_format(ivecs);
ivecs->rd_position_deinit();
+ setMessagePattern();
if (ovecs) {
+ setMessagePattern(ovecs.fmtname);
Vecs::prepare_format(ovecs);
ovecs->wr_position_deinit();
+ setMessagePattern();
}
if (ovecs && ovecs.isDynamic()) {
if (!did_something) {
- fatal("Nothing to do! Use '%s -h' for command-line options.\n", prog_name);
+ gbFatal("Nothing to do! Use '%s -h' for command-line options.\n", prog_name);
}
return 0;
#error Visual Studio 2017 and earlier are not supported. Please use Visual Studio 2019 or 2022.
#endif
+ setMessagePattern();
+
if constexpr (DEBUG_LOCALE) {
- printf("Initial locale: %s\n",setlocale(LC_ALL, nullptr));
+ gbDebug("Initial locale: %s\n",setlocale(LC_ALL, nullptr));
}
// Create a QCoreApplication object to handle application initialization.
// as opposed to the initial default "C" locale.
// This was demonstrated with Qt5 on Mac OS X.
if constexpr (DEBUG_LOCALE) {
- printf("Locale after initial setup: %s\n",setlocale(LC_ALL, nullptr));
+ gbDebug("Locale after initial setup: %s\n",setlocale(LC_ALL, nullptr));
}
// As recommended in QCoreApplication reset the locale to the default.
// Note the documentation says to set LC_NUMERIC, but QCoreApplicationPrivate::initLocale()
// Perhaps we should restore LC_ALL instead of only LC_NUMERIC.
if (strcmp(setlocale(LC_NUMERIC,nullptr), "C") != 0) {
if constexpr (DEBUG_LOCALE) {
- printf("Resetting LC_NUMERIC\n");
+ gbDebug("Resetting LC_NUMERIC\n");
}
setlocale(LC_NUMERIC,"C");
if constexpr (DEBUG_LOCALE) {
- printf("LC_ALL: %s\n",setlocale(LC_ALL, nullptr));
+ gbDebug("LC_ALL: %s\n",setlocale(LC_ALL, nullptr));
}
}
/* reset LC_TIME for strftime */
if (strcmp(setlocale(LC_TIME,nullptr), "C") != 0) {
if constexpr (DEBUG_LOCALE) {
- printf("Resetting LC_TIME\n");
+ gbDebug("Resetting LC_TIME\n");
}
setlocale(LC_TIME,"C");
if constexpr (DEBUG_LOCALE) {
- printf("LC_ALL: %s\n",setlocale(LC_ALL, nullptr));
+ gbDebug("LC_ALL: %s\n",setlocale(LC_ALL, nullptr));
}
}
- qInstallMessageHandler(MessageHandler);
(void) new gpsbabel::UsAsciiCodec(); /* make sure a US-ASCII codec is available */
gpsbabel_time = current_time().toTime_t(); /* frozen in testmode */
if (!gpsbabel_testmode()) { /* within testo ? */
- global_opts.inifile = inifile_init(QString(), MYNAME);
+ global_opts.inifile = inifile_init(QString());
}
assert(GPS_Lookup_Datum_Index("OSGB36") == kDatumOSGB36);
name.append(suffix);
}
} else {
- fatal("mkshort failure, the specified short length is insufficient.\n");
+ gbFatal("mkshort failure, the specified short length is insufficient.\n");
}
}
void MakeShort::set_length(int l)
{
if (l < 0) {
- fatal("mkshort: short length must be non-negative.\n");
+ gbFatal("mkshort: short length must be non-negative.\n");
} else if (l == 0) {
target_len_ = default_target_len;
} else {
void MakeShort::set_defname(const char* s)
{
if (s == nullptr) {
- fatal("set_defname called without a valid name.");
+ gbFatal("set_defname called without a valid name.\n");
}
defname_ = s;
}
#include "src/core/datetime.h" // for DateTime
-#define MYNAME "mtk_logger"
-
#define MTK_EVT_BITMASK (1<<0x02)
#define MTK_EVT_PERIOD (1<<0x03)
#define MTK_EVT_DISTANCE (1<<0x04)
void MtkLoggerBase::dbg(int l, const char* msg, ...)
{
- va_list ap;
- va_start(ap, msg);
if (global_opts.debug_level >= l) {
- vfprintf(stderr,msg, ap);
- fflush(stderr);
+ va_list ap;
+ va_start(ap, msg);
+ gbVLegacyLog(QtDebugMsg, msg, ap);
+ va_end(ap);
}
- va_end(ap);
}
// Returns a fully qualified pathname to a temporary file that is a copy
dbg(6, "Send %s ", cmd);
int rc = gbser_print(fd, cmd);
if (rc != gbser_OK) {
- fatal(MYNAME ": Write error (%d)\n", rc);
+ gbFatal("Write error (%d)\n", rc);
}
return cmdLen;
if (strncmp(cmd, CMD_LOG_ERASE, 12) == 0) {
cmd_erase = 1;
if (global_opts.verbose_status || global_opts.debug_level > 0) {
- fprintf(stderr, "Erasing ");
+ gbDebug("Erasing ");
}
}
// dbg(6, "## Send '%s' -- Expect '%s' in %d sec\n", cmd, expect, timeout_sec);
- do_send_cmd(cmd, strlen(cmd)); // success or fatal()...
+ do_send_cmd(cmd, strlen(cmd)); // success or gbFatal()...
int done = 0;
int loops = 0;
if (rc == gbser_TIMEOUT && time(nullptr) > tout) {
dbg(2, "NMEA command '%s' timeout !\n", cmd);
return -1;
- // fatal(MYNAME "do_cmd(): Read error (%d)\n", rc);
+ // gbFatal("do_cmd(): Read error (%d)\n", rc);
}
len = -1;
} else {
dbg(8, "Read %d bytes: '%s'\n", len, line);
if (cmd_erase && (global_opts.verbose_status || (global_opts.debug_level > 0 && global_opts.debug_level <= 3))) {
// erase cmd progress wheel -- only for debug level 1-3
- fprintf(stderr,"\b%c", LIVE_CHAR[loops%4]);
- fflush(stderr);
+ gbDebug("\b%c", LIVE_CHAR[loops%4]);
}
if (len > 5 && line[0] == '$') {
if (expect_len > 0 && strncmp(&line[1], expect, expect_len) == 0) {
if (cmd_erase && (global_opts.verbose_status || global_opts.debug_level > 0)) {
- fprintf(stderr,"\n");
+ gbDebug("\n");
}
dbg(6, "NMEA command success !\n");
if ((len - 4) > expect_len) { // alloc and copy data segment...
errno = 0;
dbg(1, "Opening port %s...\n", port);
if ((fd = gbser_init(port)) == nullptr) {
- fatal(MYNAME ": Can't initialise port \"%s\" (%s)\n", port, strerror(errno));
+ gbFatal("Can't initialise port \"%s\" (%s)\n", port, strerror(errno));
}
// verify that we have a MTK based logger...
}
if (rc) {
dbg(1, "Set baud rate to %d failed (%d)\n", MTK_BAUDRATE, rc);
- fatal(MYNAME ": Failed to set baudrate !\n");
+ gbFatal("Failed to set baudrate !\n");
}
rc = do_cmd("$PMTK605*31\r\n", "PMTK705,", &model, 10);
if (rc != 0) {
- fatal(MYNAME ": This is not a MTK based GPS ! (or is device turned off ?)\n");
+ gbFatal("This is not a MTK based GPS ! (or is device turned off ?)\n");
}
// say hello to GR245 to make it display "USB PROCESSING"
if (dout == nullptr) {
dout = ufopen(TEMP_DATA_BIN, "wb");
if (dout == nullptr) {
- fatal(MYNAME ": Can't create temporary file %s",
- qPrintable(TEMP_DATA_BIN));
+ gbFatal("Can't create temporary file %s\n",
+ gbLogCStr(TEMP_DATA_BIN));
}
}
fseek(dout, 0L,SEEK_END);
unsigned long dsize = ftell(dout);
if (dsize > 1024) {
- dbg(1, "Temp %s file exists. with size %lu\n", qPrintable(TEMP_DATA_BIN),
+ dbg(1, "Temp %s file exists. with size %lu\n", gbLogCStr(TEMP_DATA_BIN),
dsize);
dpos = 0;
init_scan = 1;
}
- dbg(1, "Download %s -> %s\n", port, qPrintable(TEMP_DATA_BIN));
+ dbg(1, "Download %s -> %s\n", port, gbLogCStr(TEMP_DATA_BIN));
// check log status - is logging disabled ?
do_cmd(CMD_LOG_STATUS, "PMTK182,3,7,", &fusage, 2);
dbg(1, "Download %dkB from device\n", (addr_max+1) >> 10);
if (dsize > addr_max) {
- dbg(1, "Temp %s file (%ld) is larger than data size %d. Data erased since last download !\n", qPrintable(TEMP_DATA_BIN), dsize, addr_max);
+ dbg(1, "Temp %s file (%ld) is larger than data size %d. Data erased since last download !\n", gbLogCStr(TEMP_DATA_BIN), dsize, addr_max);
fclose(dout);
dsize = 0;
init_scan = 0;
QFile::rename(TEMP_DATA_BIN, TEMP_DATA_BIN_OLD);
dout = ufopen(TEMP_DATA_BIN, "wb");
if (dout == nullptr) {
- fatal(MYNAME ": Can't create temporary file %s",
- qPrintable(TEMP_DATA_BIN));
+ gbFatal("Can't create temporary file %s\n",
+ gbLogCStr(TEMP_DATA_BIN));
}
}
unsigned int line_size = 2*read_bsize + 32; // logdata as nmea/hex.
unsigned int data_size = read_bsize + 32;
if ((line = (char*) xmalloc(line_size)) == nullptr) {
- fatal(MYNAME ": Can't allocate %u bytes for NMEA buffer\n", line_size);
+ gbFatal("Can't allocate %u bytes for NMEA buffer\n", line_size);
}
if ((data = (unsigned char*) xmalloc(data_size)) == nullptr) {
- fatal(MYNAME ": Can't allocate %u bytes for data buffer\n", data_size);
+ gbFatal("Can't allocate %u bytes for data buffer\n", data_size);
}
memset(line, '\0', line_size);
memset(data, '\0', data_size);
retry_cnt++;
goto mtk_retry;
} // else
- fatal(MYNAME "mtk_read(): Read error (%d)\n", rc);
+ gbFatal("mtk_read(): Read error (%d)\n", rc);
}
int len = strlen(line);
dbg(8, "Read %d bytes: '%s'\n", len, line);
}
} else {
if (null_len == chunk_size) { // 0x00 block - bad block....
- fprintf(stderr, "FIXME -- read bad block at 0x%.6x - retry ? skip ?\n%s\n", data_addr, line);
+ gbWarning("FIXME -- read bad block at 0x%.6x - retry ? skip ?\n%s\n", data_addr, line);
}
if (ff_len == chunk_size) { // 0xff block - read complete...
len = ff_len;
fseek(dout, addr, SEEK_SET);
if (fread(line, 1, rcvd_bsize, dout) == rcvd_bsize && memcmp(line, data, rcvd_bsize) == 0) {
dpos = addr;
- dbg(2, "%s same at %d\n", qPrintable(TEMP_DATA_BIN), addr);
+ dbg(2, "%s same at %d\n", gbLogCStr(TEMP_DATA_BIN), addr);
} else {
- dbg(2, "%s differs at %d\n", qPrintable(TEMP_DATA_BIN), addr);
+ dbg(2, "%s differs at %d\n", gbLogCStr(TEMP_DATA_BIN), addr);
init_scan = 0;
addr = dpos;
bsize = read_bsize;
} else {
fseek(dout, addr, SEEK_SET);
if (fwrite(data, 1, rcvd_bsize, dout) != rcvd_bsize) {
- fatal(MYNAME ": Failed to write temp. binary file\n");
+ gbFatal("Failed to write temp. binary file\n");
}
addr += rcvd_bsize;
if (global_opts.verbose_status || (global_opts.debug_level >= 2 && global_opts.debug_level < 5)) {
if (addr >= addr_max) {
perc = 100;
}
- fprintf(stderr, "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bReading 0x%.6x %3d %%", addr, perc);
+ gbDebug("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bReading 0x%.6x %3d %%", addr, perc);
}
}
}
fclose(dout);
}
if (global_opts.verbose_status || (global_opts.debug_level >= 2 && global_opts.debug_level < 5)) {
- fprintf(stderr,"\n");
+ gbDebug("\n");
}
// Fixme - Order or. Enable - parse - erase ??
{
FILE* cf;
- dbg(1, "Opening csv output file %s...\n", qPrintable(csv_fname));
+ dbg(1, "Opening csv output file %s...\n", gbLogCStr(csv_fname));
- // can't use gbfopen here - it will fatal() if file doesn't exist
+ // can't use gbfopen here - it will gbFatal() if file doesn't exist
if ((cf = ufopen(csv_fname, "r")) != nullptr) {
fclose(cf);
- warning(MYNAME ": CSV file %s already exist ! Cowardly refusing to overwrite.\n", qPrintable(csv_fname));
+ gbWarning("CSV file %s already exist ! Cowardly refusing to overwrite.\n", gbLogCStr(csv_fname));
return;
}
- if ((cd = gbfopen(csv_fname, "w", MYNAME)) == nullptr) {
- fatal(MYNAME ": Can't open csv file '%s'\n", qPrintable(csv_fname));
+ if ((cd = gbfopen(csv_fname, "w")) == nullptr) {
+ gbFatal("Can't open csv file '%s'\n", gbLogCStr(csv_fname));
}
/* Add the header line */
dbg(5,"Entering mtk_parse, count = %i, dataLen = %i\n", count, dataLen);
if (global_opts.debug_level > 5) {
- fprintf(stderr,"# Data block:");
+ gbDebug("# Data block:");
for (int j = 0; j<dataLen; j++) {
- fprintf(stderr,"%.2x ", data[j]);
+ gbDebug("%.2x ", data[j]);
}
- fprintf(stderr,"\n");
- fflush(stderr);
+ gbDebug("\n");
}
memset(&itm, 0, sizeof(itm));
}
} else {
if (global_opts.debug_level > 0) {
- fprintf(stderr,"#!! Invalid INFO block !! %d bytes\n >> ", dataLen);
+ gbDebug("#!! Invalid INFO block !! %d bytes\n >> ", dataLen);
for (bm=0; bm<16; bm++) {
- fprintf(stderr, "%.2x ", data[bm]);
+ gbDebug("%.2x ", data[bm]);
}
- fprintf(stderr,"\n");
+ gbDebug("\n");
}
return 0;
}
for (int i = 0; i<32; i++) {
if ((1U<<i) & bitmask) {
if (i > DISTANCE && global_opts.debug_level > 0) {
- warning(MYNAME ": Unknown size/meaning of bit %d\n", i);
+ gbWarning("Unknown size/meaning of bit %d\n", i);
}
if ((i == SID || i == ELEVATION || i == AZIMUTH || i == SNR) && (1U<<SID) & bitmask) {
len += log_type[i].size*32; // worst case, max sat. count..
void MtkLoggerBase::file_init(const QString& fname)
{
- dbg(4, "Opening file %s...\n", qPrintable(fname));
+ dbg(4, "Opening file %s...\n", gbLogCStr(fname));
if (fl = ufopen(fname, "rb"), nullptr == fl) {
- fatal(MYNAME ": Can't open file '%s'\n", qPrintable(fname));
+ gbFatal("Can't open file '%s'\n", gbLogCStr(fname));
}
switch (mtk_device) {
case HOLUX_M241:
fseek(fl, 0L, SEEK_END);
long fsize = ftell(fl);
if (fsize <= 0) {
- fatal(MYNAME ": File has size %ld\n", fsize);
+ gbFatal("File has size %ld\n", fsize);
}
fseek(fl, 0L, SEEK_SET);
*/
-#include <cctype> // for isprint
+#include <cassert> // for assert
#include <cmath> // for fabs
#include <cstdio> // for snprintf, sscanf, fprintf, fputc, stderr
#include <cstring> // for strncmp, strchr, strlen, strstr, memset, strrchr
#include <QDateTime> // for QDateTime
#include <QDebug> // for QDebug
#include <QList> // for QList
+#include <QRegularExpression> // for QRegularExpression
#include <QString> // for QString
#include <QStringList> // for QStringList
#include <QTextStream> // for hex
#include <QThread> // for QThread
#include <QTime> // for QTime
-#include <Qt> // for UTC
#include <QtGlobal> // for qPrintable, foreach
#include "defs.h"
sentence is truncated - and missing part of the line, including the checksum.
*/
-#define MYNAME "nmea"
-
/*
* Slightly different than the Magellan checksum fn.
*/
}
read_mode = rm_file;
- file_in = gbfopen(fname, "rb", MYNAME);
+ file_in = gbfopen(fname, "rb");
}
void
file_in = nullptr;
break;
default:
- fatal("nmea_rd_deinit: illegal read_mode.\n");
+ gbFatal("nmea_rd_deinit: illegal read_mode.\n");
break;
}
void
NmeaFormat::wr_init(const QString& fname)
{
- file_out = gbfopen(fname, opt_append ? "a+" : "w+", MYNAME);
+ file_out = gbfopen(fname, opt_append ? "a+" : "w+");
sleepms = -1;
if (opt_sleep) {
if (!prev_datetime.date().isValid()) {
if (!optdate) {
- warning(MYNAME ": No date found within track (all points dropped)!\n");
- warning(MYNAME ": Please use option \"date\" to preset a valid date for those tracks.\n");
+ gbWarning("No date found within track (all points dropped)!\n");
+ gbWarning("Please use option \"date\" to preset a valid date for those tracks.\n");
track_del_head(track);
return;
}
if (optdate) {
opt_tm = QDate::fromString(optdate, u"yyyyMMdd");
if (!opt_tm.isValid()) {
- fatal(MYNAME ": Invalid date \"%s\"!\n", qPrintable(optdate));
+ gbFatal("Invalid date \"%s\"!\n", gbLogCStr(optdate));
}
}
}
datum = GPS_Lookup_Datum_Index(sdatum);
if (datum < 0) {
- fatal(MYNAME "/SonyGPS: Unsupported datum \"%s\" in source data!\n", sdatum);
+ gbFatal("/SonyGPS: Unsupported datum \"%s\" in source data!\n", sdatum);
}
}
continue;
read_mode = rm_serial;
gbser_set_speed(gbser_handle, 4800);
} else {
- fatal(MYNAME ": Could not open '%s' for position tracking.\n", qPrintable(fname));
+ gbFatal("Could not open '%s' for position tracking.\n", gbLogCStr(fname));
}
gbser_flush(gbser_handle);
if (opt_baud) {
if (!gbser_set_speed(gbser_handle, opt_baud.get_result())) {
- fatal(MYNAME ": Unable to set baud rate %s\n", qPrintable(opt_baud));
+ gbFatal("Unable to set baud rate %s\n", gbLogCStr(opt_baud));
}
}
posn_fname = fname;
}
void
-NmeaFormat::safe_print(int cnt, const char* b)
+NmeaFormat::safe_print(const QString& b)
{
- for (int i = 0; i < cnt; i++) {
- char c = isprint(b[i]) ? b[i] : '.';
- fputc(c, stderr);
- }
+ static const QRegularExpression re("[^[:print:]]");
+ assert(re.isValid());
+
+ QString str(b);
+ qDebug().noquote() << str.replace(re, ".");
}
int NmeaFormat::hunt_sirf()
for (brp = br; *brp > 0; brp++) {
if (global_opts.debug_level > 1) {
- fprintf(stderr, "Trying %d\n", *brp);
+ gbDebug("Trying %d\n", *brp);
}
/*
ibuf[0] = 0;
int rv = gbser_read_line(gbser_handle, ibuf, sizeof(ibuf), 2000, 0x0a, 0x0d);
if (global_opts.debug_level > 1) {
- safe_print(strlen(ibuf), ibuf);
+ safe_print(ibuf);
}
if (rv < 0) {
if (am_sirf == 0) {
if (global_opts.debug_level > 1) {
- warning(MYNAME ": Attempting sirf mode.\n");
+ gbWarning("Attempting sirf mode.\n");
}
/* This is tacky, we have to change speed
* to 9600bps to tell it to speak NMEA at
continue;
}
}
- fatal(MYNAME ": No data received on %s.\n", qPrintable(posn_fname));
+ gbFatal("No data received on %s.\n", gbLogCStr(posn_fname));
}
nmea_parse_one_line(ibuf);
if (lt != last_read_time) {
void nmea_fix_timestamps(route_head* track);
static bool notalkerid_strmatch(const QByteArray& s1, const char* sentenceFormatterMnemonicCode);
void nmea_parse_one_line(const QByteArray& ibuf);
- static void safe_print(int cnt, const char* b);
+ static void safe_print(const QString& b);
int hunt_sirf();
void nmea_wayptpr(const Waypoint* wpt) const;
void nmea_track_init(const route_head* unused);
#include "nukedata.h"
#if FILTERS_ENABLED
-#define MYNAME "nukedata"
void NukeDataFilter::process()
{
#include "xmlgeneric.h" // for xml_deinit, xml_init, xml_read
-#define MYNAME "osm"
-
const QStringList OsmFormat::osm_features = {
"- dummy -", /* 0 */
"aeroway", /* 1 */
QString atstr = attrv->value("id").toString();
wpt->description = "osm-id " + atstr;
if (waypoints.contains(atstr)) {
- warning(MYNAME ": Duplicate osm-id %s!\n", qPrintable(atstr));
+ gbWarning("Duplicate osm-id %s!\n", gbLogCStr(atstr));
} else {
waypoints.insert(atstr, wpt);
wpt->wpt_flags.fmt_use = 1;
auto* tmp = new Waypoint(*ctmp);
route_add_wpt(rte, tmp);
} else {
- warning(MYNAME ": Way reference id \"%s\" wasn't listed under nodes!\n", qPrintable(atstr));
+ gbWarning("Way reference id \"%s\" wasn't listed under nodes!\n", gbLogCStr(atstr));
}
}
}
#include "src/core/textstream.h" // for TextStream
-#define MYNAME "OZI"
#define BADCHARS ",\r\n"
#define DAYS_SINCE_1990 25569
OziFormat::ozi_open_io(const QString& fname, QIODevice::OpenModeFlag mode)
{
stream = new gpsbabel::TextStream;
- stream->open(fname, mode, MYNAME, opt_codec.get().toUtf8());
+ stream->open(fname, mode, opt_codec.get().toUtf8());
if (mode & QFile::WriteOnly) {
stream->setRealNumberNotation(QTextStream::FixedNotation);
altunit = 'f';
alt_scale = FEET_TO_METERS(1.0); /* feet */
} else {
- fatal(MYNAME ": Unknown value (%s) for option 'altunit'!\n", qPrintable(altunit_opt));
+ gbFatal("Unknown value (%s) for option 'altunit'!\n", gbLogCStr(altunit_opt));
}
if (direction != 0) {
alt_scale = 1.0 / alt_scale;
proxunit = 'k';
prox_scale = 1000.0; /* kilometers */
} else {
- fatal(MYNAME ": Unknown value (%s) for option 'proxunit'!\n", qPrintable(proxunit_opt));
+ gbFatal("Unknown value (%s) for option 'proxunit'!\n", gbLogCStr(proxunit_opt));
}
if (direction != 0) {
prox_scale = 1.0 / prox_scale;
}
ozi_init_units(1);
- parse_distance(proximityarg, &proximity, 1.0 / prox_scale, MYNAME);
+ parse_distance(proximityarg, &proximity, 1.0 / prox_scale);
}
void
datum = GPS_Lookup_Datum_Index(buff);
if (datum < 0) {
- fatal(MYNAME ": Unsupported datum '%s'.\n", qPrintable(buff));
+ gbFatal("Unsupported datum '%s'.\n", gbLogCStr(buff));
}
} else if (linecount == 3) {
if (buff.startsWith( "Altitude is in ", Qt::CaseInsensitive)) {
altunit = 'm';
alt_scale = 1.0;
} else {
- fatal(MYNAME ": Unknown unit (%s) used by altitude values!\n", qPrintable(unit));
+ gbFatal("Unknown unit (%s) used by altitude values!\n", gbLogCStr(unit));
}
}
} else if ((linecount == 5) && (ozi_objective == trkdata)) {
ozi_parse_waypt(i, s, wpt_tmp, fsdata);
break;
case posndata:
- fatal(MYNAME ": realtime positioning not supported.\n");
+ gbFatal("realtime positioning not supported.\n");
break;
}
i++;
}
break;
case posndata:
- fatal(MYNAME ": realtime positioning not supported.\n");
+ gbFatal("realtime positioning not supported.\n");
break;
}
#include <QString> // for QString
#include <QtGlobal> // for qPrintable
-#include "defs.h" // for case_ignore_strcmp, fatal, grid_type, KPH_TO_MPS, MPH_TO_MPS, warning, FEET_TO_METERS, KNOTS_TO_MPS, kDatumWGS84, FATHOMS_TO_METERS, MILES_TO_METERS, NMILES_TO_METERS, parse_coordinates, CSTR, parse_distance, parse_double, parse_integer, parse_speed
+#include "defs.h" // for case_ignore_strcmp, gbFatal, grid_type, KPH_TO_MPS, MPH_TO_MPS, gbWarning, FEET_TO_METERS, KNOTS_TO_MPS, kDatumWGS84, FATHOMS_TO_METERS, MILES_TO_METERS, NMILES_TO_METERS, parse_coordinates, CSTR, parse_distance, parse_double, parse_integer, parse_speed
#include "jeeps/gpsmath.h" // for GPS_Math_Known_Datum_To_WGS84_M, GPS_Math_Swiss_EN_To_WGS84, GPS_Math_UKOSMap_To_WGS84_H, GPS_Math_UTM_EN_To_Known_Datum
result = stoi(ss, &pos, base);
} catch (const std::invalid_argument&) {
if (ok == nullptr) {
- fatal("%s: conversion to integer failed: invalid argument \"%s\".\n",
- qPrintable(id), qPrintable(str));
+ gbFatal("%s: conversion to integer failed: invalid argument \"%s\".\n",
+ gbLogCStr(id), gbLogCStr(str));
} else {
*ok = false;
return 0;
}
} catch (const std::out_of_range&) {
if (ok == nullptr) {
- fatal("%s: conversion to integer failed: out of range \"%s\".\n",
- qPrintable(id), qPrintable(str));
+ gbFatal("%s: conversion to integer failed: out of range \"%s\".\n",
+ gbLogCStr(id), gbLogCStr(str));
} else {
*ok = false;
return 0;
}
} catch (...) {
if (ok == nullptr) {
- fatal("%s: conversion to integer failed: unknown exception \"%s\".\n",
- qPrintable(id), qPrintable(str));
+ gbFatal("%s: conversion to integer failed: unknown exception \"%s\".\n",
+ gbLogCStr(id), gbLogCStr(str));
} else {
*ok = false;
return 0;
QString remainder = QString::fromStdString(ss.erase(0, pos));
if ((end == nullptr) && !remainder.trimmed().isEmpty()) {
if (ok == nullptr) {
- fatal("%s: conversion to integer failed: conversion of \"%s\" failed due to unexpected trailing data \"%s\".\n",
- qPrintable(id), qPrintable(str), qPrintable(remainder));
+ gbFatal("%s: conversion to integer failed: conversion of \"%s\" failed due to unexpected trailing data \"%s\".\n",
+ gbLogCStr(id), gbLogCStr(str), gbLogCStr(remainder));
} else {
*ok = false;
return 0;
result = stod(ss, &pos);
} catch (const std::invalid_argument&) {
if (ok == nullptr) {
- fatal("%s: conversion to double failed: invalid argument \"%s\".\n",
- qPrintable(id), qPrintable(str));
+ gbFatal("%s: conversion to double failed: invalid argument \"%s\".\n",
+ gbLogCStr(id), gbLogCStr(str));
} else {
*ok = false;
return 0.0;
}
} catch (const std::out_of_range&) {
if (ok == nullptr) {
- fatal("%s: conversion to double failed: out of range \"%s\".\n",
- qPrintable(id), qPrintable(str));
+ gbFatal("%s: conversion to double failed: out of range \"%s\".\n",
+ gbLogCStr(id), gbLogCStr(str));
} else {
*ok = false;
return 0.0;
}
} catch (...) {
if (ok == nullptr) {
- fatal("%s: conversion to double failed: unknown exception \"%s\".\n",
- qPrintable(id), qPrintable(str));
+ gbFatal("%s: conversion to double failed: unknown exception \"%s\".\n",
+ gbLogCStr(id), gbLogCStr(str));
} else {
*ok = false;
return 0.0;
QString remainder = QString::fromStdString(ss.erase(0, pos));
if ((end == nullptr) && !remainder.trimmed().isEmpty()) {
if (ok == nullptr) {
- fatal("%s: conversion to double failed: conversion of \"%s\" failed due to unexpected trailing data \"%s\".\n",
- qPrintable(id), qPrintable(str), qPrintable(remainder));
+ gbFatal("%s: conversion to double failed: conversion of \"%s\" failed due to unexpected trailing data \"%s\".\n",
+ gbLogCStr(id), gbLogCStr(str), gbLogCStr(remainder));
} else {
*ok = false;
return 0.0;
* str: input string, i.e. "128.2 km" or "22mi"
* val: pointer to resulting value
* scale: scaling parameter for unit-less values
- * module: calling module, i.e. "garmin_txt"
*/
int
-parse_distance(const QString& str, double* val, double scale, const char* module)
+parse_distance(const QString& str, double* val, double scale)
{
if (str.isEmpty()) {
return 0;
QString unit;
constexpr bool* dieonfailure = nullptr;
- *val = parse_double(str, module, dieonfailure, &unit);
+ *val = parse_double(str, "", dieonfailure, &unit);
if (fabs(*val) + 1 >= 1.0e25) {
return 0; /* not only Garmin uses this as 'unknown value' */
} else if (case_ignore_strcmp(unit, "fa") == 0) {
*val = FATHOMS_TO_METERS(*val);
} else {
- fatal("%s: Unsupported distance unit in item '%s'!\n", module, qPrintable(str));
+ gbFatal("Unsupported distance unit in item '%s'!\n", gbLogCStr(str));
}
return 2;
}
* str: input string, i.e. "22.3 km/h" or "40mph"
* val: pointer to resulting value
* scale: scaling parameter for unit-less values
- * module: calling module, i.e. "garmin_txt"
*/
int
-parse_speed(const QString& str, double* val, const double scale, const char* module)
+parse_speed(const QString& str, double* val, const double scale)
{
if (str.isEmpty()) {
QString unit;
constexpr bool* dieonfailure = nullptr;
- *val = parse_double(str, module, dieonfailure, &unit);
+ *val = parse_double(str, "", dieonfailure, &unit);
unit = unit.trimmed();
} else if (case_ignore_strcmp(unit, "mih") == 0) {
*val = MPH_TO_MPS(*val);
} else {
- warning("%s: Unsupported speed unit '%s' in item '%s'!\n", module, qPrintable(unit), qPrintable(str));
+ gbWarning("Unsupported speed unit '%s' in item '%s'!\n", gbLogCStr(unit), gbLogCStr(str));
}
return 2;
int
parse_coordinates(const char* str, int datum, const grid_type grid,
- double* latitude, double* longitude, const char* module)
+ double* latitude, double* longitude)
{
double lat;
double lon;
valid = (ct == 3);
if (valid) {
if (! GPS_Math_UKOSMap_To_WGS84_H(map, lx, ly, &lat, &lon))
- fatal("%s: Unable to convert BNG coordinates (%s)!\n",
- module, str);
+ gbFatal("Unable to convert BNG coordinates (%s)!\n",
+ str);
}
lathemi = lonhemi = '\0';
break;
valid = (ct == 4);
if (valid) {
if (! GPS_Math_UTM_EN_To_Known_Datum(&lat, &lon, utme, utmn, utmz, utmc, datum))
- fatal("%s: Unable to convert UTM coordinates (%s)!\n",
- module, str);
+ gbFatal("Unable to convert UTM coordinates (%s)!\n",
+ str);
}
lathemi = lonhemi = '\0';
break;
}
default:
/* this should never happen in a release version */
- fatal("%s/util: Unknown grid in parse_coordinates (%d)!\n",
- module, (int)grid);
+ gbFatal("Unknown grid in parse_coordinates (%d)!\n",
+ (int)grid);
}
if (! valid) {
- warning("%s: sscanf error using format \"%s\"!\n", module, format);
- warning("%s: parsing has stopped at parameter number %d.\n", module, ct);
- fatal("%s: could not convert coordinates \"%s\"!\n", module, str);
+ gbWarning("sscanf error using format \"%s\"!\n", format);
+ gbWarning("parsing has stopped at parameter number %d.\n", ct);
+ gbFatal("could not convert coordinates \"%s\"!\n", str);
}
if (lathemi == 'S') {
int
parse_coordinates(const QString& str, int datum, const grid_type grid,
- double* latitude, double* longitude, const char* module)
+ double* latitude, double* longitude)
{
return parse_coordinates(CSTR(str), datum, grid,
- latitude, longitude, module);
+ latitude, longitude);
}
#if FILTERS_ENABLED
-#define MYNAME "Polygon filter"
/*
* This test for insideness is essentially an odd/even test. The
QString line;
gpsbabel::TextStream stream;
- stream.open(polyfileopt, QIODevice::ReadOnly, MYNAME);
+ stream.open(polyfileopt, QIODevice::ReadOnly);
double olat = BADVAL;
double olon = BADVAL;
int argsfound = sscanf(CSTR(line), "%lf %lf", &lat2, &lon2);
if ((argsfound != 2) && (line.trimmed().size() > 0)) {
- warning(MYNAME
- ": Warning: Polygon file contains unusable vertex on line %d.\n",
+ gbWarning("Warning: Polygon file contains unusable vertex on line %d.\n",
fileline);
} else if (lat1 != BADVAL && lon1 != BADVAL &&
lat2 != BADVAL && lon2 != BADVAL) {
#include "src/core/datetime.h" // for DateTime
#if FILTERS_ENABLED
-#define MYNAME "Position filter"
/* tear through a waypoint queue, processing points by distance */
void PositionFilter::position_runqueue(const WaypointList& waypt_list, int qtype)
check_time = false;
if (distopt) {
- if (parse_distance(distopt, &pos_dist, kMetersPerFoot, MYNAME) == 0) {
- fatal(MYNAME ": No distance specified with distance option.\n");
+ if (parse_distance(distopt, &pos_dist, kMetersPerFoot) == 0) {
+ gbFatal("No distance specified with distance option.\n");
}
}
#include "src/core/logging.h" // for Fatal
-#define MYNAME "Qstarz BL-1000"
-
-
enum BL1000_POINT_TYPE {
BL1000_POINT_TYPE_UNKNOWN = '-',
BL1000_POINT_TYPE_WAY_POINT = 'B', // Button push
stream >> unused2;
if (stream.status() != QDataStream::Ok) {
- fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Perhaps this isn't a Qstarz BL-1000 file");
+ gbFatal(FatalMsg() << "File format error on " << fname << ". Perhaps this isn't a Qstarz BL-1000 file");
}
BL1000_POINT_TYPE type;
default:
type = BL1000_POINT_TYPE_UNKNOWN;
- fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Unexpected value for RCR (record reason): " << rcr);
+ gbFatal(FatalMsg() << "File format error on " << fname << ". Unexpected value for RCR (record reason): " << rcr);
break;
}
fix = fix_unknown;
if (type != BL1000_POINT_TYPE_UNKNOWN) {
- fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Unexpected value for fix quality: " << fixQuality);
+ gbFatal(FatalMsg() << "File format error on " << fname << ". Unexpected value for fix quality: " << fixQuality);
}
break;
// qDebug(waypoint)
if ((waypoint->latitude < -90) || (waypoint->latitude > 90)) {
- fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Unexpected value for latitude: " << waypoint->latitude);
+ gbFatal(FatalMsg() << "File format error on " << fname << ". Unexpected value for latitude: " << waypoint->latitude);
}
if ((waypoint->longitude < -180) || (waypoint->longitude > 180)) {
- fatal(FatalMsg() << MYNAME << ": File format error on " << fname << ". Unexpected value for longitude: " << waypoint->longitude);
+ gbFatal(FatalMsg() << "File format error on " << fname << ". Unexpected value for longitude: " << waypoint->longitude);
}
waypoint->altitude = altitude;
{
QFile file(fname);
if (!file.open(QIODevice::ReadOnly)) {
- fatal(FatalMsg() << MYNAME << ": Error opening file " << fname);
+ gbFatal(FatalMsg() << "Error opening file " << fname);
}
QDataStream stream(&file);
#if FILTERS_ENABLED
-#define MYNAME "Radius filter"
void RadiusFilter::process()
{
pos_dist = 0;
if (distopt) {
- if (parse_distance(distopt, &pos_dist, kMetersPerMile, MYNAME) == 0) {
- fatal(MYNAME ": No distance specified with distance option.\n");
+ if (parse_distance(distopt, &pos_dist, kMetersPerMile) == 0) {
+ gbFatal("No distance specified with distance option.\n");
}
}
-radius(lat): conversion to double failed: conversion of "44x" failed due to unexpected trailing data "x".
+radius: radius(lat): conversion to double failed: conversion of "44x" failed due to unexpected trailing data "x".
-stack(depth): conversion to integer failed: invalid argument "b".
+stack: stack(depth): conversion to integer failed: invalid argument "b".
-gdb(bitscategory): conversion to integer failed: conversion of "0x2z" failed due to unexpected trailing data "z".
+gdb: gdb(bitscategory): conversion to integer failed: conversion of "0x2z" failed due to unexpected trailing data "z".
-csv(snlen): conversion to integer failed: invalid argument "a".
+csv: csv(snlen): conversion to integer failed: invalid argument "a".
-TX: Frame Start a0 a2 Payload_Len 0003 Cmd: getfileheader
-RX: Start a0a2 Len 0005 Cmd: getfileheader
-found 0 headers, nextheader=0
-no further headers, aborting the loop
-TX: Frame Start a0 a2 Payload_Len 0001 Cmd: getconfig
-RX: Start a0a2 Len 002e Cmd: getconfig
-TX: Frame Start a0 a2 Payload_Len 0003 Cmd: erase
-RX: Start a0a2 Len 0005 Cmd: erase
+dg-200-bin: options: module/option=value: dg-200-bin/erase="1"
+dg-200-bin: options: module/option=value: dg-200-bin/erase_only="0" (=default)
+dg-200-bin: TX: Frame Start a0 a2 Payload_Len 0003 Cmd: getfileheader
+dg-200-bin: RX: Start a0a2 Len 0005 Cmd: getfileheader
+dg-200-bin: found 0 headers, nextheader=0
+dg-200-bin: no further headers, aborting the loop
+dg-200-bin: TX: Frame Start a0 a2 Payload_Len 0001 Cmd: getconfig
+dg-200-bin: RX: Start a0a2 Len 002e Cmd: getconfig
+dg-200-bin: TX: Frame Start a0 a2 Payload_Len 0003 Cmd: erase
+dg-200-bin: RX: Start a0a2 Len 0005 Cmd: erase
+gpx: options: module/option=value: gpx/snlen="32" (=default)
+gpx: options: module/option=value: gpx/elevprec="3" (=default)
-mkshort failure, the specified short length is insufficient.
+xcsv: mkshort failure, the specified short length is insufficient.
-trackfilter-init: Found track point at -36.720713,142.176768 without time!
+track: init: Found track point at -36.720713,142.176768 without time!
-
-Processing waypts
-point ct: 2, waypt_count: 2
-
-Processing routes
-route 0 ct: 2, waypt_count: 2, segments 1
-route head ct: 1, route_count: 1, total segment count: 1
-total route point ct: 2, route_waypt_count: 2
-
-Processing tracks
-track 0 ct: 2, waypt_count: 2, segments 1
-track head ct: 1, track_count: 1, total segment count: 1
-total track point ct: 2, track_waypt_count: 2
+validate:
+validate: Processing waypts
+validate: point ct: 2, waypt_count: 2
+validate:
+validate: Processing routes
+validate: route 0 ct: 2, waypt_count: 2, segments 1
+validate: route head ct: 1, route_count: 1, total segment count: 1
+validate: total route point ct: 2, route_waypt_count: 2
+validate:
+validate: Processing tracks
+validate: track 0 ct: 2, waypt_count: 2, segments 1
+validate: track head ct: 1, track_count: 1, total segment count: 1
+validate: total track point ct: 2, track_waypt_count: 2
-validate:No input
+validate: No input
#include <QTextStream> // for qSetRealNumberPrecision
#include <QtGlobal> // for qDebug, qint64
-#include "defs.h" // for Waypoint, route_head, fatal, WaypointList, track_add_wpt, track_disp_all, RouteList, track_add_head, track_del_wpt, track_swap, UrlList, gb_color, global_options, global_opts
+#include "defs.h" // for Waypoint, route_head, gbFatal, WaypointList, track_add_wpt, track_disp_all, RouteList, track_add_head, track_del_wpt, track_swap, UrlList, gb_color, global_options, global_opts
#include "src/core/datetime.h" // for DateTime
#include "src/core/logging.h" // for FatalMsg
#include "src/core/nvector.h" // for NVector
#if FILTERS_ENABLED
-#define MYNAME "resample"
-
void ResampleFilter::average_waypoint(Waypoint* wpt, bool zero_stuffed)
{
{
if (interpolateopt) {
if (track_count() == 0) {
- fatal(FatalMsg() << MYNAME ": Found no tracks to operate on.");
+ gbFatal(FatalMsg() << "Found no tracks to operate on.");
}
auto interpolate_rte_lambda = [this](const route_head* rte)->void {
if (decimateopt) {
if (track_count() == 0) {
- fatal(FatalMsg() << MYNAME ": Found no tracks to operate on.");
+ gbFatal(FatalMsg() << "Found no tracks to operate on.");
}
auto decimate_rte_lambda = [this](const route_head* rte)->void {
if (averageopt) {
average_count = averageopt.get_result();
if (average_count < 2) {
- fatal(FatalMsg() << MYNAME ": the average count must be greater than one.");
+ gbFatal(FatalMsg() << "the average count must be greater than one.");
}
}
if (decimateopt) {
decimate_count = decimateopt.get_result();
if (decimate_count < 2) {
- fatal(FatalMsg() << MYNAME ": the decimate count must be greater than one.");
+ gbFatal(FatalMsg() << "the decimate count must be greater than one.");
}
}
if (interpolateopt) {
interpolate_count = interpolateopt.get_result();
if (interpolate_count < 2) {
- fatal(FatalMsg() << MYNAME ": the interpolate count must be greater than one.");
+ gbFatal(FatalMsg() << "the interpolate count must be greater than one.");
}
if (!averageopt || average_count < interpolate_count) {
- fatal(FatalMsg() << MYNAME ": the average option must be used with interpolation, and the average count must be greater than or equal to the interpolation count.");
+ gbFatal(FatalMsg() << "the average option must be used with interpolation, and the average count must be greater than or equal to the interpolation count.");
}
}
}
#if FILTERS_ENABLED
-#define MYNAME "Route reversal filter"
-
/*
* reverse_route_wpt fixes up the waypoint flag new_trkseg
*/
case trkdata:
break;
default:
- fatal(MYNAME ": This filter only works in track "
- "or route (-t or -r) mode.\n");
+ gbFatal("This filter only works in track or route (-t or -r) mode.\n");
}
}
#include <QString> // for QString, QTypeInfo<>::isRelocatable
#include <QtGlobal> // for qPrintable
-#include "defs.h" // for fatal, color_to_bbggrr
+#include "defs.h" // for gbFatal, color_to_bbggrr
/*
* Colors derived from http://www.w3.org/TR/SVG/types.html#ColorKeywords
return (entry.b << 16) + (entry.g << 8) + entry.r;
}
- fatal("unrecognized color name %s\n", qPrintable(cname));
+ gbFatal("unrecognized color name %s\n", gbLogCStr(cname));
return -1;
}
if (!session_list.isEmpty()) {
return &session_list.last();
} else {
- fatal("Attempt to fetch session outside of session range.");
+ gbFatal("Attempt to fetch session outside of session range.\n");
}
}
#endif
-#define MYNAME "shape"
-
/************************************************************************/
/* SHPOpenGpsbabel() */
/************************************************************************/
[[noreturn]] void ShapeFormat::dump_fields() const
{
char name[12];
- warning(MYNAME ": Database fields:\n");
+ gbWarning("Database fields:\n");
const int nFields = DBFGetFieldCount(ihandledb);
for (int i = 0; i < nFields; i++) {
DBFFieldType type = DBFGetFieldInfo(ihandledb, i, name, nullptr, nullptr);
- warning(MYNAME ": Field Index: %2d, Field Name: %12s, Field Type %d\n", i, name, type);
+ gbWarning("Field Index: %2d, Field Name: %12s, Field Type %d\n", i, name, type);
}
- fatal("\n");
+ gbFatal("\n");
}
void ShapeFormat::check_field_index(const int fieldIdx) const
{
const int maxFields = DBFGetFieldCount(ihandledb);
if (fieldIdx < 0 || fieldIdx >= maxFields) {
- warning(MYNAME ": dbf file for %s doesn't have a field index number %d.\n", qPrintable(ifname), fieldIdx);
- warning(MYNAME ": the minimum field number is 0 and the maximum field number is %d.\n",maxFields-1);
+ gbWarning("dbf file for %s doesn't have a field index number %d.\n", gbLogCStr(ifname), fieldIdx);
+ gbWarning("the minimum field number is 0 and the maximum field number is %d.\n",maxFields-1);
dump_fields();
}
}
{
const int fieldIdx = DBFGetFieldIndex(ihandledb, CSTR(fieldName));
if (fieldIdx < 0) {
- warning(MYNAME ": dbf file for %s doesn't have a field named '%s'.\n", qPrintable(ifname), qPrintable(fieldName));
+ gbWarning("dbf file for %s doesn't have a field named '%s'.\n", gbLogCStr(ifname), gbLogCStr(fieldName));
dump_fields();
}
return fieldIdx;
// TODO: The .prj file can define the the coordinate system and projection information.
ihandle = SHPOpenGpsbabel(fname, "rb");
if (ihandle == nullptr) {
- fatal(MYNAME ": Cannot open shp file %s for reading\n", qPrintable(ifname));
+ gbFatal("Cannot open shp file %s for reading\n", gbLogCStr(ifname));
}
ihandledb = DBFOpenGpsbabel(fname, "rb");
if (ihandledb == nullptr) {
- fatal(MYNAME ": Cannot open dbf file %s for reading\n", qPrintable(ifname));
+ gbFatal("Cannot open dbf file %s for reading\n", gbLogCStr(ifname));
}
const char* codepage = DBFGetCodePage(ihandledb);
if (codepage) {
QString qcodepage(codepage);
if (qcodepage.compare(u"UTF-8", Qt::CaseInsensitive)) {
- warning(MYNAME ": dbf file %s is in code page %s, but we always process dbf files as UTF-8.\n",qPrintable(ifname),codepage);
+ gbWarning("dbf file %s is in code page %s, but we always process dbf files as UTF-8.\n",gbLogCStr(ifname),codepage);
}
} else {
- warning(MYNAME ": dbf file %s uses unknown code page, assuming UTF-8.\n", qPrintable(ifname));
+ gbWarning("dbf file %s uses unknown code page, assuming UTF-8.\n", gbLogCStr(ifname));
}
}
default:
err:
- warning("This file contains shapefile geometry type %s that does not naturally convert\nCustom programming is likely required.\n",
+ gbWarning("This file contains shapefile geometry type %s that does not naturally convert\nCustom programming is likely required.\n",
etype);
break;
}
ohandle = SHPCreateGpsbabel(ofname, SHPT_POINT);
if (ohandle == nullptr) {
- fatal(MYNAME ": Cannot open shp file %s for writing\n",
- qPrintable(ofname));
+ gbFatal("Cannot open shp file %s for writing\n",
+ gbLogCStr(ofname));
}
ohandledb = DBFCreateExGpsbabel(ofname, "UTF-8\n");
if (ohandledb == nullptr) {
- fatal(MYNAME ": Cannot open dbf file %s for writing\n",
- qPrintable(ofname));
+ gbFatal("Cannot open dbf file %s for writing\n",
+ gbLogCStr(ofname));
}
nameFieldIdx=DBFAddField(ohandledb,"name",FTString,100,0);
auto write_wpt_lambda = [this](const Waypoint* wpt)->void {
ohandle = SHPCreateGpsbabel(ofname, SHPT_ARC);
if (ohandle == nullptr) {
- fatal(MYNAME ": Cannot open shp file %s for writing\n",
- qPrintable(ofname));
+ gbFatal("Cannot open shp file %s for writing\n",
+ gbLogCStr(ofname));
}
ohandledb = DBFCreateExGpsbabel(ofname, "UTF-8\n");
if (ohandledb == nullptr) {
- fatal(MYNAME ": Cannot open dbf file %s for writing\n",
- qPrintable(ofname));
+ gbFatal("Cannot open dbf file %s for writing\n",
+ gbLogCStr(ofname));
}
nameFieldIdx=DBFAddField(ohandledb,"name",FTString,100,0);
auto poly_init_lambda = [this](const route_head* rte)->void {
break;
}
case posndata:
- fatal(MYNAME ": Realtime positioning not supported\n");
+ gbFatal("Realtime positioning not supported\n");
break;
}
}
#include "gbser.h" // for gbser_set_speed, gbser_OK, gbser_deinit
-#define MYNAME "skytraq"
-
#define TIMEOUT 5000
#define SECTOR_SIZE 4096
#define FULL_ITEM_LEN 18
void
-SkytraqBase::db(int l, const char* msg, ...)
+SkytraqBase::dbg(int l, const char* msg, ...)
{
- va_list ap;
- va_start(ap, msg);
if (global_opts.debug_level >= l) {
- vprintf(msg, ap);
+ va_list ap;
+ va_start(ap, msg);
+ gbVLegacyLog(QtDebugMsg, msg, ap);
+ va_end(ap);
}
- va_end(ap);
}
void
-SkytraqBase::rd_drain() const
+SkytraqBase::rd_drain()
{
if (gbser_flush(serial_handle)) {
- db(1, MYNAME ": rd_drain(): Comm error\n");
+ dbg(1, "rd_drain(): Comm error\n");
}
}
int
-SkytraqBase::rd_char(int* errors) const
+SkytraqBase::rd_char(int* errors)
{
while (*errors > 0) {
int c = gbser_readc_wait(serial_handle, TIMEOUT);
if (c < 0) {
- db(1, MYNAME ": rd_char(): Got error: %d\n", c);
+ dbg(1, "rd_char(): Got error: %d\n", c);
(*errors)--;
} else {
- db(4, "rd_char(): Got char: %02x '%c'\n", c, isprint(c) ? c : '.');
+ dbg(4, "rd_char(): Got char: %02x '%c'\n", c, isprint(c) ? c : '.');
return c;
}
}
- fatal(MYNAME ": Too many read errors on serial port\n");
+ gbFatal("Too many read errors on serial port\n");
return -1;
}
int
-SkytraqBase::rd_buf(uint8_t* buf, int len) const
+SkytraqBase::rd_buf(uint8_t* buf, int len)
{
char dump[16*3+16+2];
printf("len=%i skytraq_baud=%i timeout=%i\n", len, skytraq_baud, timeout);*/
int rc = gbser_read_wait(serial_handle, (void*)buf, len, timeout);
if (rc < 0) {
- db(1, MYNAME ": rd_buf(): Read error (%d)\n", rc);
+ dbg(1, "rd_buf(): Read error (%d)\n", rc);
return res_ERROR;
} else if (rc < len) {
- db(1, MYNAME ": rd_buf(): Read timeout\n");
+ dbg(1, "rd_buf(): Read timeout\n");
return res_ERROR;
}
if (global_opts.debug_level >= 4) {
- db(4, "rd_buf(): dump follows:\n");
+ dbg(4, "rd_buf(): dump follows:\n");
dump[sizeof(dump)-1] = 0;
for (int i = 0; i < (len+15)/16*16; i++) { // count to next 16-byte boundary
if (i < len) {
}
if ((i+1)%16 == 0) {
dump[16*3] = ' '; // gets overwritten with 0 by snprintf
- db(4, "%s\n", dump);
+ dbg(4, "%s\n", dump);
}
}
}
}
int
-SkytraqBase::rd_word() const
+SkytraqBase::rd_word()
{
int errors = 5; /* allow this many errors */
int c;
c = rd_char(&errors);
if (c < 0) {
- db(1, MYNAME ": rd_word(): Got error: %d\n", c);
+ dbg(1, "rd_word(): Got error: %d\n", c);
return -1;
}
buffer[0] = c;
c = rd_char(&errors);
if (c < 0) {
- db(1, MYNAME ": rd_word(): Got error: %d\n", c);
+ dbg(1, "rd_word(): Got error: %d\n", c);
return -1;
}
buffer[1] = c;
/* if (rd_buf(buffer, 2) != res_OK) {
- db(1, MYNAME ": rd_word(): Read error\n");
+ dbg(1, "rd_word(): Read error\n");
return res_ERROR;
}*/
}
void
-SkytraqBase::wr_char(int c) const
+SkytraqBase::wr_char(int c)
{
int rc;
- db(4, "Sending: %02x '%c'\n", (unsigned)c, isprint(c) ? c : '.');
+ dbg(4, "Sending: %02x '%c'\n", (unsigned)c, isprint(c) ? c : '.');
if (rc = gbser_writec(serial_handle, c), gbser_OK != rc) {
- fatal(MYNAME ": Write error (%d)\n", rc);
+ gbFatal("Write error (%d)\n", rc);
}
}
void
-SkytraqBase::wr_buf(const unsigned char* str, int len) const
+SkytraqBase::wr_buf(const unsigned char* str, int len)
{
for (int i = 0; i < len; i++) {
wr_char(str[i]);
}
int
-SkytraqBase::skytraq_rd_msg(void* payload, unsigned int len) const
+SkytraqBase::skytraq_rd_msg(void* payload, unsigned int len)
{
int errors = 5; // Allow this many receiver errors silently.
unsigned int c;
}
}
if (state < sizeof(MSG_START)) {
- db(1, MYNAME ": Didn't get message start tag\n");
+ dbg(1, "Didn't get message start tag\n");
return res_ERROR;
}
if ((rcv_len = rd_word()) < (signed int)len) {
if (rcv_len >= 0) { /* negative values indicate receive errors */
- db(1, MYNAME ": Received message too short (got %i bytes, expected %u)\n",
+ dbg(1, "Received message too short (got %i bytes, expected %u)\n",
rcv_len, len);
return res_PROTOCOL_ERR;
}
}
/* at this point, we have rcv_len >= len >= 0 */
- db(2, "Receiving message with %i bytes of payload (expected >=%u)\n", rcv_len, len);
+ dbg(2, "Receiving message with %i bytes of payload (expected >=%u)\n", rcv_len, len);
rd_buf((uint8_t*) payload, len);
unsigned int calc_cs = skytraq_calc_checksum((const unsigned char*) payload, len);
unsigned int rcv_cs = rd_char(&errors);
if (rcv_cs != calc_cs) {
- fatal(MYNAME ": Checksum error: got 0x%02x, expected 0x%02x\n", rcv_cs, calc_cs);
+ gbFatal("Checksum error: got 0x%02x, expected 0x%02x\n", rcv_cs, calc_cs);
}
if (rd_word() != 0x0D0A) {
- fatal(MYNAME ": Didn't get message end tag (CR/LF)\n");
+ gbFatal("Didn't get message end tag (CR/LF)\n");
}
return res_OK;
}
void
-SkytraqBase::skytraq_wr_msg(const uint8_t* payload, int len) const
+SkytraqBase::skytraq_wr_msg(const uint8_t* payload, int len)
{
rd_drain();
}
int
-SkytraqBase::skytraq_expect_ack(uint8_t id) const
+SkytraqBase::skytraq_expect_ack(uint8_t id)
{
uint8_t ack_msg[2];
//int rcv_len;
if (skytraq_rd_msg(ack_msg, sizeof(ack_msg)) == res_OK) {
if (ack_msg[0] == 0x83) {
if (ack_msg[1] == id) {
- db(3, "Got ACK (id=0x%02x)\n", id);
+ dbg(3, "Got ACK (id=0x%02x)\n", id);
return res_OK;
} else if (ack_msg[1] == 0) {
/* some (all?) devices first send an ACK with id==0, skip that */
continue;
} else {
- db(1, MYNAME ": Warning: Got unexpected ACK (id=0x%02x)\n", ack_msg[1]);
+ dbg(1, "Warning: Got unexpected ACK (id=0x%02x)\n", ack_msg[1]);
continue;
}
} else if (ack_msg[0] == 0x84) {
- db(3, "Warning: Got NACK (id=0x%02x)\n", ack_msg[1]);
+ dbg(3, "Warning: Got NACK (id=0x%02x)\n", ack_msg[1]);
return res_NACK;
} else {
- db(3, "Warning: Got unexpected message (id=0x%02x), expected ACK (id=0x%02x)\n",
+ dbg(3, "Warning: Got unexpected message (id=0x%02x), expected ACK (id=0x%02x)\n",
ack_msg[0], id);
}
} else {
}
int
-SkytraqBase::skytraq_expect_msg(uint8_t id, uint8_t* payload, int len) const
+SkytraqBase::skytraq_expect_msg(uint8_t id, uint8_t* payload, int len)
{
for (int i = 0; i < MSG_RETRIES; i++) {
int rc = skytraq_rd_msg(payload, len);
}
int
-SkytraqBase::skytraq_wr_msg_verify(const uint8_t* payload, int len) const
+SkytraqBase::skytraq_wr_msg_verify(const uint8_t* payload, int len)
{
for (int i = 0; i < MSG_RETRIES; i++) {
if (i > 0) {
- db(1, "resending msg (id=0x%02x)...\n", payload[0]);
+ dbg(1, "resending msg (id=0x%02x)...\n", payload[0]);
}
skytraq_wr_msg(payload, len);
int rc = skytraq_expect_ack(payload[0]);
if (rc == res_OK || rc == res_NACK) {
return rc;
}
- db(1, MYNAME ": Got neither ACK nor NACK, ");
+ dbg(1, "Got neither ACK nor NACK, ");
}
- db(1, "aborting (msg id was 0x%02x).\n", payload[0]);
+ dbg(1, "aborting (msg id was 0x%02x).\n", payload[0]);
return res_ERROR;
}
int
-SkytraqBase::skytraq_system_restart() const
+SkytraqBase::skytraq_system_restart()
{
uint8_t MSG_SYSTEM_RESTART[15] =
{ 0x01, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
- db(2, "restart system\n");
+ dbg(2, "restart system\n");
return skytraq_wr_msg_verify(MSG_SYSTEM_RESTART, sizeof(MSG_SYSTEM_RESTART));
}
int
-SkytraqBase::skytraq_set_baud(int baud) const
+SkytraqBase::skytraq_set_baud(int baud)
{
/* Note: according to AN0003_v3.pdf, attrib == 0x00 means write to SRAM only, however
* it seems to write to flash too. The Windows software sends 0x02 so we do here too.
uint8_t MSG_CONFIGURE_SERIAL_PORT[4]
= { 0x05, 0x00, 0x00, 0x02 };
- db(2, "Setting baud rate to %i\n", baud);
+ dbg(2, "Setting baud rate to %i\n", baud);
switch (baud) {
case 4800:
MSG_CONFIGURE_SERIAL_PORT[2] = 6;
break;
default:
- fatal(MYNAME ": Unsupported baud rate: %ibd\n", baud);
+ gbFatal("Unsupported baud rate: %ibd\n", baud);
}
int rc = skytraq_wr_msg_verify(MSG_CONFIGURE_SERIAL_PORT, sizeof(MSG_CONFIGURE_SERIAL_PORT));
if (rc != res_OK) {
- db(2, "Warning: error setting skytraq device baud rate\n");
+ dbg(2, "Warning: error setting skytraq device baud rate\n");
return rc;
}
- db(3, "Now setting UART baud rate to %i\n", baud);
+ dbg(3, "Now setting UART baud rate to %i\n", baud);
rd_drain();
if (gbser_set_speed(serial_handle, baud) != gbser_OK) {
- db(2, "Warning: error setting uart baud rate\n");
+ dbg(2, "Warning: error setting uart baud rate\n");
return res_ERROR;
}
}
int
-SkytraqBase::skytraq_configure_logging() const
+SkytraqBase::skytraq_configure_logging()
{
// an0008-1.4.14: logs if
// (dt > tmin & dd >= dmin & v >= vmin) | dt > tmax | dd > dmax | v > vmax
if (!opt_configure_logging.isEmpty()) {
unsigned int nn = sscanf(opt_configure_logging.get().toUtf8(), "%u:%u:%u:%u", &tmin, &tmax, &dmin, &dmax);
if (nn>3) {
- db(0, "Reconfiguring logging to: tmin=%u, tmax=%u, dmin=%u, dmax=%u\n", tmin, tmax, dmin, dmax);
+ dbg(0, "Reconfiguring logging to: tmin=%u, tmax=%u, dmin=%u, dmax=%u\n", tmin, tmax, dmin, dmax);
be_write32(MSG_LOG_CONFIGURE_CONTROL+5, tmin);
be_write32(MSG_LOG_CONFIGURE_CONTROL+1, tmax);
be_write32(MSG_LOG_CONFIGURE_CONTROL+13, dmin);
be_write32(MSG_LOG_CONFIGURE_CONTROL+9, dmax);
} else {
- db(1, MYNAME "Option usage: configlog=tmin:tmax:dmin:dmax");
+ dbg(1, "Option usage: configlog=tmin:tmax:dmin:dmax");
return -1;
}
}
}
int
-SkytraqBase::skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* sectors_free, uint16_t* sectors_total) const
+SkytraqBase::skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* sectors_free, uint16_t* sectors_total)
{
uint8_t MSG_LOG_STATUS_CONTROL = 0x17;
struct {
unsigned int rc;
if ((rc = skytraq_wr_msg_verify(&MSG_LOG_STATUS_CONTROL, 1)) != res_OK) { /* get memory status */
- db(1, MYNAME ": Error sending LOG STATUS CONTROL message (%d)\n", rc);
+ dbg(1, "Error sending LOG STATUS CONTROL message (%d)\n", rc);
return res_ERROR;
}
rc = skytraq_expect_msg(0x94, (uint8_t*)&MSG_LOG_STATUS_OUTPUT, sizeof(MSG_LOG_STATUS_OUTPUT));
if (rc < sizeof(MSG_LOG_STATUS_OUTPUT)) {
- db(1, MYNAME ": Didn't receive expected reply (%d)\n", rc);
+ dbg(1, "Didn't receive expected reply (%d)\n", rc);
return res_ERROR;
}
unsigned int vmin = le_readu32(&MSG_LOG_STATUS_OUTPUT.min_speed);
// log_bool = *(MSG_LOG_STATUS_OUTPUT.datalog_enable);
// fifo_mode = *(MSG_LOG_STATUS_OUTPUT.log_fifo_mode);
- db(1, "#logging: tmin=%u, tmax=%u, dmin=%u, dmax=%u, vmin=%u, vmax=%u\n", tmin, tmax, dmin, dmax, vmin, vmax);
+ dbg(1, "#logging: tmin=%u, tmax=%u, dmin=%u, dmax=%u, vmin=%u, vmax=%u\n", tmin, tmax, dmin, dmax, vmin, vmax);
return res_OK;
}
}
QDateTime
-SkytraqBase::gpstime_to_qdatetime(int week, int sec) const
+SkytraqBase::gpstime_to_qdatetime(int week, int sec)
{
/* Notes:
* * week rollover period can be specified using option
}
Waypoint*
-SkytraqBase::make_trackpoint(read_state* st, double lat, double lon, double alt) const
+SkytraqBase::make_trackpoint(read_state* st, double lat, double lon, double alt)
{
auto* wpt = new Waypoint;
#define ITEM_SPEED(item) (item->type_and_speed[1] | ((item->type_and_speed[0] & 0x0F) << 8))
int
-SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len) const
+SkytraqBase::process_data_item(read_state* pst, const item_frame* pitem, int len)
{
int res = 0;
double lat;
case 0x2: /* Multi HZ item */
if (len < MULTI_HZ_ITEM_LEN) {
- db(1, MYNAME ": Not enough bytes in sector for a full item.\n");
+ dbg(1, "Not enough bytes in sector for a full item.\n");
return res_ERROR;
}
m.gps_week = ITEM_WEEK_NUMBER(pitem);
spe = KPH_TO_MPS(be_read16(pitem->multi_hz.v_kmh));
- db(4, "Got multi hz item: week=%i sec=%i lat=%i lon=%i alt=%i speed=%f\n",
+ dbg(4, "Got multi hz item: week=%i sec=%i lat=%i lon=%i alt=%i speed=%f\n",
m.gps_week, m.gps_sec,
m.lat, m.lon, m.alt,
spe);
case 0x4: /* full item */
if (len < FULL_ITEM_LEN) {
- db(1, MYNAME ": Not enough bytes in sector for a full item.\n");
+ dbg(1, "Not enough bytes in sector for a full item.\n");
return res_ERROR;
}
ts = me_read32(pitem->full.ts);
pst->y = f.y;
pst->z = f.z;
- db(4, "Got %s item: week=%i sec=%i x=%i y=%i z=%i speed=%i\n",
+ dbg(4, "Got %s item: week=%i sec=%i x=%i y=%i z=%i speed=%i\n",
poi ? "POI" : "full",
f.gps_week, f.gps_sec,
f.x, f.y, f.z,
case 0x8: /* compact item */
if (len < COMPACT_ITEM_LEN) {
- db(1, MYNAME ": Not enough bytes in sector for a compact item.\n");
+ dbg(1, "Not enough bytes in sector for a compact item.\n");
return res_ERROR;
}
c.dx = (pitem->comp.dpos[1] >> 6) | (pitem->comp.dpos[0] << 2);
}
c.dt = (pitem->comp.dt[0] << 8) | pitem->comp.dt[1];
- db(4, "Got compact item: dt=%i dx=%i dy=%i dz=%i speed=%i uu=%i\n",
+ dbg(4, "Got compact item: dt=%i dx=%i dy=%i dz=%i speed=%i uu=%i\n",
c.dt, c.dx, c.dy, c.dz,
ITEM_SPEED(pitem), (pitem->comp.dpos[2] & 0x0F)>>2);
break;
default:
- db(1, MYNAME ": Unknown item type encountered: 0x%02x\n", ITEM_TYPE(pitem));
+ dbg(1, "Unknown item type encountered: 0x%02x\n", ITEM_TYPE(pitem));
return 0;
}
}
if (nullptr == pst->route_head_) {
- db(1, MYNAME ": New Track\n");
+ dbg(1, "New Track\n");
pst->route_head_ = new route_head;
track_add_head(pst->route_head_);
}
}
int /* returns number of bytes processed (terminates on 0xFF i.e. empty or padding bytes) */
-SkytraqBase::process_data_sector(read_state* pst, const uint8_t* buf, int len) const
+SkytraqBase::process_data_sector(read_state* pst, const uint8_t* buf, int len)
{
int plen;
int ilen;
for (plen = 0; plen < len && buf[plen] != 0xFF; plen += ilen) {
ilen = process_data_item(pst, reinterpret_cast<const item_frame*>(&buf[plen]), len-plen);
if (ilen <= 0) {
- fatal(MYNAME ": Error %i while processing data item #%i (starts at %i)\n",
+ gbFatal("Error %i while processing data item #%i (starts at %i)\n",
ilen, pst->tpn, plen);
}
}
/* Note: the buffer is being padded with 0xFFs if necessary so there are always SECTOR_SIZE valid bytes */
int
-SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const
+SkytraqBase::skytraq_read_single_sector(unsigned int sector, uint8_t* buf)
{
uint8_t MSG_LOG_SECTOR_READ_CONTROL[2] = { 0x1B, (uint8_t)(sector) };
int errors = 5; /* allow this many errors */
uint8_t buffer[16];
if (sector > 0xFF) {
- fatal(MYNAME ": Invalid sector number (%i)\n", sector);
+ gbFatal("Invalid sector number (%i)\n", sector);
}
- db(2, "Reading sector #%i...\n", sector);
+ dbg(2, "Reading sector #%i...\n", sector);
if (skytraq_wr_msg_verify((uint8_t*)&MSG_LOG_SECTOR_READ_CONTROL, sizeof(MSG_LOG_SECTOR_READ_CONTROL)) != res_OK) {
- db(1, MYNAME ": Didn't receive ACK\n");
+ dbg(1, "Didn't receive ACK\n");
return res_ERROR;
}
}
}
if (j < sizeof(SECTOR_READ_END)) {
- db(1, MYNAME ": Didn't get sector end tag\n");
+ db(1, "Didn't get sector end tag\n");
return res_ERROR;
}
c = rd_char(&errors); /* read checksum byte */
}
}
if (j < sizeof(SECTOR_READ_END)) {
- db(1, MYNAME ": Didn't get sector end tag\n");
+ dbg(1, "Didn't get sector end tag\n");
return res_ERROR;
}
if (c < 16) {
}
#endif
i = i-j;
- db(3, "Received %i bytes of log data\n", i);
+ dbg(3, "Received %i bytes of log data\n", i);
//#define SINGLE_READ_WORKAROUND
#ifdef SINGLE_READ_WORKAROUND
cs = skytraq_calc_checksum(buf, i);
if (cs != buf[i+sizeof(SECTOR_READ_END)]) {
- db(1, MYNAME ": Checksum error while reading sector: got 0x%02x, expected 0x%02x\n",
+ dbg(1, "Checksum error while reading sector: got 0x%02x, expected 0x%02x\n",
buf[i+sizeof(SECTOR_READ_END)], cs);
return res_ERROR;
}
}
int
-SkytraqBase::skytraq_read_multiple_sectors(int first_sector, unsigned int sector_count, uint8_t* buf) const
+SkytraqBase::skytraq_read_multiple_sectors(int first_sector, unsigned int sector_count, uint8_t* buf)
{
uint8_t MSG_LOG_READ_MULTI_SECTORS[5] = { 0x1D };
unsigned int i;
if (first_sector < 0 || first_sector > 0xFFFF) {
- fatal(MYNAME ": Invalid sector number (%i)\n", first_sector);
+ gbFatal("Invalid sector number (%i)\n", first_sector);
}
be_write16(&MSG_LOG_READ_MULTI_SECTORS[1], first_sector);
if (sector_count > 0xFFFF) {
- fatal(MYNAME ": Invalid sector count (%i)\n", sector_count);
+ gbFatal("Invalid sector count (%i)\n", sector_count);
}
be_write16(&MSG_LOG_READ_MULTI_SECTORS[3], sector_count);
- db(2, "Reading %i sectors beginning from #%i...\n", sector_count, first_sector);
+ dbg(2, "Reading %i sectors beginning from #%i...\n", sector_count, first_sector);
unsigned int read_result = skytraq_wr_msg_verify((uint8_t*)&MSG_LOG_READ_MULTI_SECTORS, sizeof(MSG_LOG_READ_MULTI_SECTORS));
if (read_result != res_OK) {
}
for (i = 0; i < sector_count; i++) {
- db(2, "Receiving data of sector #%i...\n", first_sector+i);
+ dbg(2, "Receiving data of sector #%i...\n", first_sector+i);
rd_buf(buf+i*SECTOR_SIZE, SECTOR_SIZE);
}
rd_buf(buf+SECTOR_SIZE*sector_count, sizeof(SECTOR_READ_END)+6);
uint8_t* buf_end_tag = buf + SECTOR_SIZE*sector_count;
for (i = 0; i < sizeof(SECTOR_READ_END); i++) {
if (buf_end_tag[i] != SECTOR_READ_END[i]) {
- db(1, MYNAME ": Wrong end tag: got 0x%02x ('%c'), expected 0x%02x ('%c')\n",
+ dbg(1, "Wrong end tag: got 0x%02x ('%c'), expected 0x%02x ('%c')\n",
buf_end_tag[i], isprint(buf_end_tag[i]) ? buf_end_tag[i] : '.',
SECTOR_READ_END[i], isprint(SECTOR_READ_END[i]) ? SECTOR_READ_END[i] : '.');
return res_ERROR;
unsigned int cs = skytraq_calc_checksum(buf, SECTOR_SIZE*sector_count);
if (cs != buf_end_tag[sizeof(SECTOR_READ_END)]) {
- db(1, MYNAME ": Checksum error while reading sector: got 0x%02x, expected 0x%02x\n",
+ dbg(1, "Checksum error while reading sector: got 0x%02x, expected 0x%02x\n",
buf_end_tag[sizeof(SECTOR_READ_END)], cs);
return res_ERROR;
}
}
void
-SkytraqBase::skytraq_read_tracks() const
+SkytraqBase::skytraq_read_tracks()
{
read_state st;
uint32_t log_wr_ptr;
state_init(&st);
if (skytraq_get_log_buffer_status(&log_wr_ptr, §ors_free, §ors_total) != res_OK) {
- fatal(MYNAME ": Can't get log buffer status\n");
+ gbFatal("Can't get log buffer status\n");
}
- db(1, MYNAME ": Device status: free sectors: %i / total sectors: %i / %i%% used / write ptr: %i\n",
+ dbg(1, "Device status: free sectors: %i / total sectors: %i / %i%% used / write ptr: %i\n",
sectors_free, sectors_total, 100 - sectors_free*100 / sectors_total, log_wr_ptr);
if (opt_first_sector_val >= sectors_total) {
- db(1, "Warning: sector# specified by option first-sector (%i) is beyond reported total sector count (%i)",
+ dbg(1, "Warning: sector# specified by option first-sector (%i) is beyond reported total sector count (%i)",
opt_first_sector_val, sectors_total);
}
/* Workaround: sectors_free is sometimes reported wrong. Tried to use log_wr_ptr as an
} else {
sectors_used = opt_last_sector_val;
if (opt_last_sector_val >= sectors_total) {
- db(1, "Warning: sector# specified by option last-sector (%i) is beyond reported total sector count (%i)",
+ dbg(1, "Warning: sector# specified by option last-sector (%i) is beyond reported total sector count (%i)",
opt_last_sector_val, sectors_total);
}
}
// m.ad/090930: removed code that tried reducing read_at_once if necessary since doesn't work with xmalloc
if (opt_dump_file) {
- dumpfile = gbfopen(opt_dump_file, "w", MYNAME);
+ dumpfile = gbfopen(opt_dump_file, "w");
}
- db(1, MYNAME ": Reading log data from device...\n");
- db(1, MYNAME ": start=%d used=%d\n", opt_first_sector_val, sectors_used);
- db(1, MYNAME ": opt_last_sector_val=%d\n", opt_last_sector_val);
+ dbg(1, "Reading log data from device...\n");
+ dbg(1, "start=%d used=%d\n", opt_first_sector_val, sectors_used);
+ dbg(1, "opt_last_sector_val=%d\n", opt_last_sector_val);
for (int i = opt_first_sector_val; i < sectors_used; i += got_sectors) {
for (t = 0, got_sectors = 0; (t < SECTOR_RETRIES) && (got_sectors <= 0); t++) {
if (opt_read_at_once.get_result() == 0 || multi_read_supported == 0) {
break;
case res_NACK:
- db(1, MYNAME ": Device doesn't seem to support reading multiple "
+ dbg(1, "Device doesn't seem to support reading multiple "
"sectors at once, falling back to single read.\n");
multi_read_supported = 0;
break;
}
}
if (got_sectors <= 0) {
- fatal(MYNAME ": Error reading sector %i\n", i);
+ gbFatal("Error reading sector %i\n", i);
}
total_sectors_read += got_sectors;
}
for (int s = 0; s < got_sectors; s++) {
- db(4, MYNAME ": Decoding sector #%i...\n", i+s);
+ dbg(4, "Decoding sector #%i...\n", i+s);
rc = process_data_sector(&st, buffer+s*SECTOR_SIZE, SECTOR_SIZE);
if (rc == 0) {
- db(1, MYNAME ": Empty sector encountered: apparently only %i sectors are "
+ dbg(1, "Empty sector encountered: apparently only %i sectors are "
"used but device reported %i.\n",
i+s, sectors_used);
i = sectors_used; /* terminate to avoid reading stale data still in the logger */
break;
} else if (rc >= (4096-FULL_ITEM_LEN) && i+s+1 >= sectors_used && i+s+1 < sectors_total) {
- db(1, MYNAME ": Last sector is nearly full, reading one more sector\n");
+ dbg(1, "Last sector is nearly full, reading one more sector\n");
sectors_used++;
}
}
}
free(buffer);
- db(1, MYNAME ": Got %i trackpoints from %i sectors.\n", st.tpn, total_sectors_read);
+ dbg(1, "Got %i trackpoints from %i sectors.\n", st.tpn, total_sectors_read);
if (dumpfile) {
gbfclose(dumpfile);
}
int
-SkytraqBase::skytraq_probe() const
+SkytraqBase::skytraq_probe()
{
int baud_rates[] = { 9600, 230400, 115200, 57600, 4800, 19200, 38400 };
int baud_rates_count = sizeof(baud_rates)/sizeof(baud_rates[0]);
}
for (int i = 0; i < baud_rates_count; i++) {
- db(1, MYNAME ": Probing SkyTraq Venus at %ibaud...\n", baud_rates[i]);
+ dbg(1, "Probing SkyTraq Venus at %ibaud...\n", baud_rates[i]);
rd_drain();
if (int rc = gbser_set_speed(serial_handle, baud_rates[i]); rc != gbser_OK) {
- db(1, MYNAME ": Set baud rate to %d failed (%d), retrying...\n", baud_rates[i], rc);
+ dbg(1, "Set baud rate to %d failed (%d), retrying...\n", baud_rates[i], rc);
if (int rc = gbser_set_speed(serial_handle, baud_rates[i]); rc != gbser_OK) {
- db(1, MYNAME ": Set baud rate to %d failed (%d)\n", baud_rates[i], rc);
+ dbg(1, "Set baud rate to %d failed (%d)\n", baud_rates[i], rc);
continue;
}
}
skytraq_wr_msg(MSG_QUERY_SOFTWARE_VERSION, /* get firmware version */
sizeof(MSG_QUERY_SOFTWARE_VERSION));
if (int rc = skytraq_expect_ack(0x02); rc != res_OK) {
- db(2, "Didn't receive ACK (%d), retrying...\n", rc);
+ dbg(2, "Didn't receive ACK (%d), retrying...\n", rc);
skytraq_wr_msg(MSG_QUERY_SOFTWARE_VERSION, /* get firmware version */
sizeof(MSG_QUERY_SOFTWARE_VERSION));
if (int rc = skytraq_expect_ack(0x02); rc != res_OK) {
- db(2, "Didn't receive ACK (%d)\n", rc);
+ dbg(2, "Didn't receive ACK (%d)\n", rc);
continue;
}
}
}*/
if (int rc = skytraq_expect_msg(0x80, (uint8_t*)&MSG_SOFTWARE_VERSION, sizeof(MSG_SOFTWARE_VERSION));
rc < (int)sizeof(MSG_SOFTWARE_VERSION)) {
- db(2, "Didn't receive expected reply (%d)\n", rc);
+ dbg(2, "Didn't receive expected reply (%d)\n", rc);
} else {
- db(1, MYNAME ": Venus device found: Kernel version = %i.%i.%i, ODM version = %i.%i.%i, "\
+ dbg(1, "Venus device found: Kernel version = %i.%i.%i, ODM version = %i.%i.%i, "\
"revision (Y/M/D) = %02i/%02i/%02i\n",
MSG_SOFTWARE_VERSION.kernel_ver[1], MSG_SOFTWARE_VERSION.kernel_ver[2],
MSG_SOFTWARE_VERSION.kernel_ver[3],
}
int
-SkytraqBase::skytraq_erase() const
+SkytraqBase::skytraq_erase()
{
uint8_t MSG_LOG_ERASE = 0x19;
- db(1, MYNAME ": Erasing logger memory...\n");
+ dbg(1, "Erasing logger memory...\n");
if (skytraq_wr_msg_verify(&MSG_LOG_ERASE, sizeof(MSG_LOG_ERASE)) != res_OK) {
- db(1, MYNAME ": Didn't receive ACK\n");
+ dbg(1, "Didn't receive ACK\n");
return res_ERROR;
}
}
void
-SkytraqBase::skytraq_set_location() const
+SkytraqBase::skytraq_set_location()
{
double lat;
double lng;
uint8_t MSG_SET_LOCATION[17] = { 0x36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
uint8_t MSG_GET_LOCATION = 0x35;
- db(3, MYNAME ": set_location='%s'\n", qPrintable(opt_set_location));
+ dbg(3, "set_location='%s'\n", gbLogCStr(opt_set_location));
sscanf(opt_set_location.get().toUtf8(), "%lf:%lf", &lat, &lng);
le_write_double(&MSG_SET_LOCATION[1], lat);
le_write_double(&MSG_SET_LOCATION[9], lng);
for (unsigned char i : MSG_SET_LOCATION) {
- db(3, "%02x ", i);
+ dbg(3, "%02x ", i);
}
- db(3, "\n");
+ dbg(3, "\n");
if (skytraq_wr_msg_verify((uint8_t*)&MSG_SET_LOCATION, sizeof(MSG_SET_LOCATION)) != res_OK) {
- fatal(MYNAME ": cannot set new location\n");
+ gbFatal("cannot set new location\n");
}
{
char buf[32];
SkytraqBase::skytraq_rd_init(const QString& fname)
{
if ((serial_handle = gbser_init(qPrintable(fname))) == nullptr) {
- fatal(MYNAME ": Can't open port '%s'\n", qPrintable(fname));
+ gbFatal("Can't open port '%s'\n", gbLogCStr(fname));
}
if ((skytraq_baud = skytraq_probe()) <= 0) {
- fatal(MYNAME ": Can't find skytraq device on '%s'\n", qPrintable(fname));
+ gbFatal("Can't find skytraq device on '%s'\n", gbLogCStr(fname));
}
}
}
void
-SkytraqBase::skytraq_read() const
+SkytraqBase::skytraq_read()
{
if (opt_set_location) {
skytraq_set_location();
void
SkytraqfileFormat::rd_init(const QString& fname)
{
- db(1, "Opening file...\n");
- if ((file_handle = gbfopen(fname, "rb", MYNAME)) == nullptr) {
- fatal(MYNAME ": Can't open file '%s'\n", qPrintable(fname));
+ dbg(1, "Opening file...\n");
+ if ((file_handle = gbfopen(fname, "rb")) == nullptr) {
+ gbFatal("Can't open file '%s'\n", gbLogCStr(fname));
}
}
void
SkytraqfileFormat::rd_deinit()
{
- db(1, "Closing file...\n");
+ dbg(1, "Closing file...\n");
gbfclose(file_handle);
file_handle = nullptr;
}
auto* buffer = (uint8_t*) xmalloc(SECTOR_SIZE);
if (opt_first_sector_val > 0) {
- db(4, MYNAME ": Seeking to first-sector index %i\n", opt_first_sector_val*SECTOR_SIZE);
+ dbg(4, "Seeking to first-sector index %i\n", opt_first_sector_val*SECTOR_SIZE);
gbfseek(file_handle, opt_first_sector_val*SECTOR_SIZE, SEEK_SET);
}
- db(1, MYNAME ": Reading log data from file...\n");
+ dbg(1, "Reading log data from file...\n");
int sectors_read = 0;
while ((got_bytes = gbfread(buffer, 1, SECTOR_SIZE, file_handle)) > 0) {
- db(4, MYNAME ": Decoding sector #%i...\n", sectors_read++);
+ dbg(4, "Decoding sector #%i...\n", sectors_read++);
int rc = process_data_sector(&st, buffer, got_bytes);
if (opt_last_sector_val < 0) {
if (rc < (4096-FULL_ITEM_LEN)) {
- db(1, MYNAME ": Empty sector encountered, terminating.\n");
+ dbg(1, "Empty sector encountered, terminating.\n");
break;
}
} else if (sectors_read-1 >= opt_last_sector_val) {
- db(1, MYNAME ": desired last-sector #%i reached, terminating.\n", sectors_read-1);
+ dbg(1, "desired last-sector #%i reached, terminating.\n", sectors_read-1);
break;
}
}
xfree(buffer);
- db(1, MYNAME ": Got %i trackpoints from %i sectors.\n", st.tpn, sectors_read);
+ dbg(1, "Got %i trackpoints from %i sectors.\n", st.tpn, sectors_read);
}
/**************************************************************************/
* http://navin.com.tw/miniHomer.htm
* 2010-10-23 Josef Reisinger
*/
-#ifdef MYNAME
-#undef MYNAME
-#endif
-#define MYNAME "miniHomer"
#define NUMPOI (sizeof poinames/sizeof poinames[0])
#ifdef DEAD_CODE_IS_REBORN
int MinihomerFormat::getPoiByName(char* name)
*ecef_y = (double)((n+lalt) * cos(llat) * sin(llng));
*ecef_z = (double)((n*(1-esqr) + lalt)* sin(llat));
}
-void MinihomerFormat::miniHomer_get_poi() const
+void MinihomerFormat::miniHomer_get_poi()
{
uint8_t MSG_GET_POI[3] = { 0x4D, 0, 0};
uint8_t buf[32];
MSG_GET_POI[1]=(poi>>8)&0xff;
MSG_GET_POI[2]=(poi)&0xff;
if (skytraq_wr_msg_verify((uint8_t*)&MSG_GET_POI, sizeof(MSG_GET_POI)) != res_OK) {
- warning(MYNAME ": cannot read poi %d '%s'\n", poi, poinames[poi]);
+ gbWarning("cannot read poi %d '%s'\n", poi, poinames[poi]);
}
skytraq_rd_msg(buf, 25);
double ecef_x = be_read_double(buf+1);
// todo - how to determine not-set POIs ?
if (ecef_x < 100.0 && ecef_y < 100.0 && ecef_z < 100.0) {
- db(2, MYNAME" : skipped poi %u for X=%f, y=%f, Z=%f\n", poi, ecef_x, ecef_y, ecef_z);
+ dbg(2, "skipped poi %u for X=%f, y=%f, Z=%f\n", poi, ecef_x, ecef_y, ecef_z);
} else {
ECEF_to_LLA(ecef_x, ecef_y, ecef_z, &lat, &lng, &alt);
wpt->longitude = lng;
wpt->altitude = alt;
waypt_add(wpt);
- db(1, MYNAME ": got POI[%s]='%f %f %f/%f %f %f'\n", poinames[poi], lat, lng, alt, ecef_x, ecef_y, ecef_z);
+ dbg(1, "got POI[%s]='%f %f %f/%f %f %f'\n", poinames[poi], lat, lng, alt, ecef_x, ecef_y, ecef_z);
}
}
}
* -1 in case of errors
* the number of the POI will not be checked - if it is not correct, miniHome will send NACK
*/
-int MinihomerFormat::miniHomer_set_poi(uint16_t poinum, const QString& opt_poi) const
+int MinihomerFormat::miniHomer_set_poi(uint16_t poinum, const QString& opt_poi)
{
#define MSG_SET_POI_SIZE (sizeof(uint8_t)+sizeof(uint16_t)+3*sizeof(double)+sizeof(uint8_t))
uint8_t MSG_SET_POI[MSG_SET_POI_SIZE] = {
*/
int n = sscanf(opt_poi.toUtf8(), "%lf:%lf:%lf", &lat, &lng, &alt);
if (n >= 2) {
- db(3, "found %d elems '%s':poi=%s@%d, lat=%f, lng=%f, alt=%f\n", n, qPrintable(opt_poi), poinames[poinum], poinum, lat, lng, alt);
+ dbg(3, "found %d elems '%s':poi=%s@%d, lat=%f, lng=%f, alt=%f\n", n, gbLogCStr(opt_poi), poinames[poinum], poinum, lat, lng, alt);
lla2ecef(lat, lng, alt, &ecef_x, &ecef_y, &ecef_z);
- db(1, MYNAME ": set POI[%s]='%f %f %f/%f %f %f'\n", poinames[poinum], lat, lng, alt, ecef_x, ecef_y, ecef_z);
+ dbg(1, "set POI[%s]='%f %f %f/%f %f %f'\n", poinames[poinum], lat, lng, alt, ecef_x, ecef_y, ecef_z);
be_write16(MSG_SET_POI+1, poinum);
be_write_double(MSG_SET_POI+3, ecef_x);
be_write_double(MSG_SET_POI+11, ecef_y);
if (skytraq_wr_msg_verify((uint8_t*)&MSG_SET_POI, sizeof(MSG_SET_POI)) == res_OK) {
result=1;
} else {
- warning(MYNAME ": cannot set poi %d '%s'\n", poinum, poinames[poinum]);
+ gbWarning("cannot set poi %d '%s'\n", poinum, poinames[poinum]);
result=-1;
}
} else {
- warning(MYNAME ": argument to %s needs to be like <lat>:<lng>[:<alt>]\n", poinames[poinum]);
+ gbWarning("argument to %s needs to be like <lat>:<lng>[:<alt>]\n", poinames[poinum]);
result=-1;
}
}
/* Member Functions */
- [[gnu::format(printf, 2, 3)]] static void db(int l, const char* msg, ...);
- void rd_drain() const;
- int rd_char(int* errors) const;
- int rd_buf(uint8_t* buf, int len) const;
- int rd_word() const;
- void wr_char(int c) const;
- void wr_buf(const unsigned char* str, int len) const;
+ [[gnu::format(printf, 2, 3)]] static void dbg(int l, const char* msg, ...);
+ void rd_drain();
+ int rd_char(int* errors);
+ int rd_buf(uint8_t* buf, int len);
+ int rd_word();
+ void wr_char(int c);
+ void wr_buf(const unsigned char* str, int len);
static int skytraq_calc_checksum(const unsigned char* buf, int len);
- int skytraq_rd_msg(void* payload, unsigned int len) const;
- void skytraq_wr_msg(const uint8_t* payload, int len) const;
- int skytraq_expect_ack(uint8_t id) const;
- int skytraq_expect_msg(uint8_t id, uint8_t* payload, int len) const;
- int skytraq_wr_msg_verify(const uint8_t* payload, int len) const;
- int skytraq_system_restart() const;
- int skytraq_set_baud(int baud) const;
- int skytraq_configure_logging() const;
- int skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* sectors_free, uint16_t* sectors_total) const;
+ int skytraq_rd_msg(void* payload, unsigned int len);
+ void skytraq_wr_msg(const uint8_t* payload, int len);
+ int skytraq_expect_ack(uint8_t id);
+ int skytraq_expect_msg(uint8_t id, uint8_t* payload, int len);
+ int skytraq_wr_msg_verify(const uint8_t* payload, int len);
+ int skytraq_system_restart();
+ int skytraq_set_baud(int baud);
+ int skytraq_configure_logging();
+ int skytraq_get_log_buffer_status(uint32_t* log_wr_ptr, uint16_t* sectors_free, uint16_t* sectors_total);
static unsigned int me_read32(const unsigned char* p);
- QDateTime gpstime_to_qdatetime(int week, int sec) const;
+ QDateTime gpstime_to_qdatetime(int week, int sec);
static void ECEF_to_LLA(double x, double y, long int z, double* lat, double* lon, double* alt);
static void state_init(read_state* pst);
- Waypoint* make_trackpoint(read_state* st, double lat, double lon, double alt) const;
- int process_data_item(read_state* pst, const item_frame* pitem, int len) const;
- int process_data_sector(read_state* pst, const uint8_t* buf, int len) const;
- int skytraq_read_single_sector(unsigned int sector, uint8_t* buf) const;
- int skytraq_read_multiple_sectors(int first_sector, unsigned int sector_count, uint8_t* buf) const;
- void skytraq_read_tracks() const;
- int skytraq_probe() const;
- int skytraq_erase() const;
- void skytraq_set_location() const;
+ Waypoint* make_trackpoint(read_state* st, double lat, double lon, double alt);
+ int process_data_item(read_state* pst, const item_frame* pitem, int len);
+ int process_data_sector(read_state* pst, const uint8_t* buf, int len);
+ int skytraq_read_single_sector(unsigned int sector, uint8_t* buf);
+ int skytraq_read_multiple_sectors(int first_sector, unsigned int sector_count, uint8_t* buf);
+ void skytraq_read_tracks();
+ int skytraq_probe();
+ int skytraq_erase();
+ void skytraq_set_location();
void skytraq_rd_init(const QString& fname);
- void skytraq_read() const;
+ void skytraq_read();
void skytraq_rd_deinit();
/* Data Members */
/* Member Functions */
static void lla2ecef(double lat, double lng, double alt, double* ecef_x, double* ecef_y, double* ecef_z);
- void miniHomer_get_poi() const;
- int miniHomer_set_poi(uint16_t poinum, const QString& opt_poi) const;
+ void miniHomer_get_poi();
+ int miniHomer_set_poi(uint16_t poinum, const QString& opt_poi);
/* Data Members */
#if FILTERS_ENABLED
-#define MYNAME "simplify"
inline bool operator<(const SimplifyRouteFilter::trackerror& lhs, const SimplifyRouteFilter::trackerror& rhs)
{
if (metric == metric_t::relative) {
// check hdop is available for compute_track_error
if (wpt->hdop == 0) {
- fatal(MYNAME ": relative needs hdop information.\n");
+ gbFatal("relative needs hdop information.\n");
}
}
} else if (countopt && !erroropt) {
limit_basis = limit_basis_t::count;
} else {
- fatal(MYNAME ": You must specify either count or error, but not both.\n");
+ gbFatal("You must specify either count or error, but not both.\n");
}
if (!lenopt && !relopt) {
} else if (!xteopt && !lenopt && relopt) {
metric = metric_t::relative;
} else {
- fatal(MYNAME ": You may specify only one of crosstrack, length, or relative.\n");
+ gbFatal("You may specify only one of crosstrack, length, or relative.\n");
}
switch (limit_basis) {
if (metric == metric_t::relative) {
error = erroropt.get_result();
} else {
- if (parse_distance(erroropt, &error, kMetersPerMile, MYNAME) == 0) {
- fatal(MYNAME ": No value specified with error option.\n");
+ if (parse_distance(erroropt, &error, kMetersPerMile) == 0) {
+ gbFatal("No value specified with error option.\n");
}
}
}
#if FILTERS_ENABLED
-#define MYNAME "sort"
-
bool SortFilter::sort_comp_wpt_by_description(const Waypoint* a, const Waypoint* b)
{
waypt_sort(sort_comp_wpt_by_time);
break;
default:
- fatal(MYNAME ": unknown waypoint sort mode.");
+ gbFatal("unknown waypoint sort mode.\n");
}
switch (rte_sort_mode) {
route_sort(sort_comp_rh_by_number);
break;
default:
- fatal(MYNAME ": unknown route sort mode.");
+ gbFatal("unknown route sort mode.\n");
}
switch (trk_sort_mode) {
track_sort(sort_comp_rh_by_number);
break;
default:
- fatal(MYNAME ": unknown track sort mode.");
+ gbFatal("unknown track sort mode.\n");
}
}
} else if (!opt_sm_description && !opt_sm_gcid && !opt_sm_shortname && opt_sm_time) {
wpt_sort_mode = SortModeWpt::time;
} else {
- fatal(MYNAME ": At most one of the options description, gcid, shortname and time may be selected.");
+ gbFatal("At most one of the options description, gcid, shortname and time may be selected.\n");
}
// sort routes by
} else if (!opt_sm_rtedesc && !opt_sm_rtename && opt_sm_rtenum) {
rte_sort_mode = SortModeRteHd::number;
} else {
- fatal(MYNAME ": At most one of the options rtedesc, rtename and rtenum may be selected.");
+ gbFatal("At most one of the options rtedesc, rtename and rtenum may be selected.\n");
}
// sort tracks by
} else if (!opt_sm_trkdesc && !opt_sm_trkname && opt_sm_trknum) {
trk_sort_mode = SortModeRteHd::number;
} else {
- fatal(MYNAME ": At most one of the options trkdesc, trkname and trknum may be selected.");
+ gbFatal("At most one of the options trkdesc, trkname and trknum may be selected.\n");
}
}
namespace gpsbabel
{
-CodecDevice::CodecDevice(const QString& fname, const char* module, const char* codec_name) :
- fname_(fname), module_(module), codec_name_(codec_name)
+CodecDevice::CodecDevice(const QString& fname, const char* codec_name) :
+ fname_(fname), codec_name_(codec_name)
{
}
codec_ = QTextCodec::codecForName(codec_name_);
if (codec_ == nullptr) {
list_codecs();
- fatal("%s: Unsupported codec '%s'.\n", module_, codec_name_);
+ gbFatal("Unsupported codec '%s'.\n", codec_name_);
// return false;
}
class CodecDevice : public QIODevice
{
public:
- CodecDevice(const QString& fname, const char* module, const char* codec_name);
+ CodecDevice(const QString& fname, const char* codec_name);
~CodecDevice();
bool open(QIODevice::OpenMode mode) override;
bool isSequential() const override;
private:
QString fname_;
- const char* module_;
const char* codec_name_;
gpsbabel::File* file_{nullptr};
QTextCodec* codec_{nullptr};
}
if (!status) {
- fatal(FatalMsg().noquote() << "Cannot open '" %
+ gbFatal(FatalMsg().noquote() << "Cannot open '" %
(gpsbabel_testmode() ?
QFileInfo(*this).fileName() :
QFileInfo(*this).absoluteFilePath()) %
};
/*
- * To use a FatalMsg pass it to fatal(), e.g.
- * fatal(FatalMsg() << "bye bye");
+ * To use a FatalMsg pass it to gbFatal(), e.g.
+ * gbFatal(FatalMsg() << "bye bye");
*
* This
- * 1) allows the noreturn attribute on fatal to be use by analysis
+ * 1) allows the noreturn attribute on gbFatal to be use by analysis
* tools such as cppcheck.
- * 2) allows fatal to throw an exception instead of calling exit.
+ * 2) allows gbFatal to throw an exception instead of calling exit.
* This could be caught by main for a cleaner exit from a fatal error.
*/
class FatalMsg : public QDebug
#include <optional> // for optional
-#include "defs.h" // for fatal, list_codecs
+#include "defs.h" // for gbFatal, list_codecs
#include "src/core/textstream.h"
#include "src/core/file.h" // for File
namespace gpsbabel
{
-void TextStream::open(const QString& fname, QIODevice::OpenMode mode, const char* module, const char* codec_name)
+void TextStream::open(const QString& fname, QIODevice::OpenMode mode, const char* codec_name)
{
std::optional<QStringConverter::Encoding> encoding = QStringConverter::encodingForName(codec_name);
bool use_stringconverter = encoding.has_value();
}
}
} else {
- device_ = new gpsbabel::CodecDevice(fname, module, codec_name);
+ device_ = new gpsbabel::CodecDevice(fname, codec_name);
bool status = device_->open(mode);
if (!status) {
- fatal("%s: device not open %d\n", module, status);
+ gbFatal("device not open %d\n", status);
}
setDevice(device_);
setEncoding(QStringConverter::Utf16);
class TextStream : public QTextStream
{
public:
- void open(const QString& fname, QIODevice::OpenMode mode, const char* module, const char* codec = "UTF-8");
+ void open(const QString& fname, QIODevice::OpenMode mode, const char* codec = "UTF-8");
void close();
private:
XmlStreamWriter::xml_stack_list_entry_t& XmlStreamWriter::activeStack()
{
if (stack_list.isEmpty()) {
- fatal("xmlstreamwriter: programming error: the stack* functions are used incorrectly.");
+ gbFatal("xmlstreamwriter: programming error: the stack* functions are used incorrectly.\n");
}
return stack_list.last();
}
#if FILTERS_ENABLED
-#define MYNAME "Stack filter"
-
void StackFilter::process()
{
stack_elt* tmp_elt = nullptr;
} else if (opt_pop) {
tmp_elt = stack;
if (!tmp_elt) {
- fatal(MYNAME ": stack empty\n");
+ gbFatal("stack empty\n");
}
if (opt_append) {
waypt_append(&(stack->waypts));
tmp_elt = stack;
while (swapdepth > 1) {
if (!tmp_elt->next) {
- fatal(MYNAME ": swap with nonexistent element\n");
+ gbFatal("swap with nonexistent element\n");
}
tmp_elt = tmp_elt->next;
swapdepth--;
}
if (invalid) {
- fatal(MYNAME ": invalid combination of options\n");
+ gbFatal("invalid combination of options\n");
}
}
stack_elt* tmp_elt = nullptr;
if (warnings_enabled && stack) {
- warning(MYNAME " Warning: leftover stack entries; "
+ gbWarning("Warning: leftover stack entries; "
"check command line for mistakes\n");
}
while (stack) {
#include "src/core/logging.h" // for Fatal
-#define MYNAME "subrip"
-
/* internal helper functions */
QTime
switch (*it) {
case '%':
if (++it == end) {
- fatal("No character after %% in subrip format.\n");
+ gbFatal("No character after %% in subrip format.\n");
}
switch (*it) {
case '\\':
if (++it == end) {
- fatal("No character after \\ in subrip format.\n");
+ gbFatal("No character after \\ in subrip format.\n");
}
switch (*it) {
gradient = 0;
if (opt_gpstime != opt_gpsdate) {
- fatal(FatalMsg() << MYNAME ": Either both or neither of the gps_date and gps_time options must be supplied!");
+ gbFatal(FatalMsg() << "Either both or neither of the gps_date and gps_time options must be supplied!");
}
gps_datetime = QDateTime();
if (opt_gpstime && opt_gpsdate) {
QDate gps_date = QDate::fromString(opt_gpsdate, u"yyyyMMdd");
if (!gps_date.isValid()) {
- fatal(FatalMsg().nospace() << MYNAME ": option gps_date value (" << opt_gpsdate.get() << ") is invalid. Expected yyyymmdd.");
+ gbFatal(FatalMsg().nospace() << "option gps_date value (" << opt_gpsdate.get() << ") is invalid. Expected yyyymmdd.");
}
QTime gps_time = QTime::fromString(opt_gpstime, u"HHmmss");
if (!gps_time.isValid()) {
gps_time = QTime::fromString(opt_gpstime, u"HHmmss.z");
if (!gps_time.isValid()) {
- fatal(FatalMsg().nospace() << MYNAME ": option gps_time value (" << opt_gpstime.get() << ") is invalid. Expected hhmmss[.sss]");
+ gbFatal(FatalMsg().nospace() << "option gps_time value (" << opt_gpstime.get() << ") is invalid. Expected hhmmss[.sss]");
}
}
gps_datetime = QDateTime(gps_date, gps_time, QtUTC);
if (!video_time.isValid()) {
video_time = QTime::fromString(opt_videotime, u"HHmmss.z");
if (!video_time.isValid()) {
- fatal(FatalMsg().nospace() << MYNAME ": option video_time value (" << opt_videotime.get() << ") is invalid. Expected hhmmss[.sss].");
+ gbFatal(FatalMsg().nospace() << "option video_time value (" << opt_videotime.get() << ") is invalid. Expected hhmmss[.sss].");
}
}
video_offset_ms = video_time.msecsSinceStartOfDay();
video_datetime = QDateTime();
- fout = gbfopen(fname, "wb", MYNAME);
+ fout = gbfopen(fname, "wb");
}
void
#include "swapdata.h"
#include <utility> // for swap
-#define MYNAME "swapdata"
#if FILTERS_ENABLED
#include "src/core/xmltag.h" // for xml_findfirst, xml_tag, xml_attribute, fs_xml, xml_findnext
-#define MYNAME "TEXT"
-
void
TextFormat::wr_init(const QString& fname)
{
output_name = fname;
if (!split_output) {
file_out = new gpsbabel::TextStream;
- file_out->open(fname, QIODevice::WriteOnly, MYNAME);
+ file_out->open(fname, QIODevice::WriteOnly);
}
mkshort_handle = new MakeShort;
if (re.match(opt_degformat).hasMatch()) {
degformat = opt_degformat.get().at(2).toLatin1();
} else {
- fatal(MYNAME ": Unrecognized degformat %s, expected 'ddd', 'dmm' or 'dms'.\n", qPrintable(opt_degformat));
+ gbFatal("Unrecognized degformat %s, expected 'ddd', 'dmm' or 'dms'.\n", gbLogCStr(opt_degformat));
}
if (opt_altunits.get().startsWith('f')) {
} else if (opt_altunits.get().startsWith('m')) {
altunits = 'm';
} else {
- fatal(MYNAME ": Unrecognized altunits %s, expected 'f' for feet or 'm' for meters.\n", qPrintable(opt_altunits));
+ gbFatal("Unrecognized altunits %s, expected 'f' for feet or 'm' for meters.\n", gbLogCStr(opt_altunits));
}
}
QString thisfname(output_name);
thisfname += QString::number(waypoint_count);
file_out = new gpsbabel::TextStream;
- file_out->open(thisfname, QIODevice::WriteOnly, MYNAME);
+ file_out->open(thisfname, QIODevice::WriteOnly);
}
GPS_Math_WGS84_To_UTM_EN(wpt->latitude, wpt->longitude,
#include "mkshort.h" // for MakeShort
-#define MYNAME "TPG"
-
#define MAXTPGSTRINGSIZE 256
#define MAXTPGOUTPUTPINS 65535
{
tpg_datum_idx = GPS_Lookup_Datum_Index(tpg_datum_opt);
if (tpg_datum_idx < 0) {
- fatal(MYNAME ": Datum '%s' is not recognized.\n", qPrintable(tpg_datum_opt));
+ gbFatal("Datum '%s' is not recognized.\n", gbLogCStr(tpg_datum_opt));
}
}
TpgFormat::rd_init(const QString& fname)
{
tpg_common_init();
- tpg_file_in = gbfopen_le(fname, "rb", MYNAME);
+ tpg_file_in = gbfopen_le(fname, "rb");
}
void
TpgFormat::wr_init(const QString& fname)
{
tpg_common_init();
- tpg_file_out = gbfopen_le(fname, "wb", MYNAME);
+ tpg_file_out = gbfopen_le(fname, "wb");
mkshort_handle = new MakeShort;
waypt_out_count = 0;
}
gbfread(&buff[0], 19, 1, tpg_file_in);
if (valid_tpg_header(buff, 19) != 0) {
- fatal(MYNAME ": input file does not appear to be a valid .TPG file.\n");
+ gbFatal("input file does not appear to be a valid .TPG file.\n");
}
}
if (s > MAXTPGOUTPUTPINS) {
- fatal(MYNAME ": attempt to output too many points (%d). The max is %d. Sorry.\n", s, MAXTPGOUTPUTPINS);
+ gbFatal("attempt to output too many points (%d). The max is %d. Sorry.\n", s, MAXTPGOUTPUTPINS);
}
/* write the waypoint count */
#include <QStringLiteral> // for qMakeStringPrivate, QStringLiteral
#include <QtGlobal> // for qPrintable, Q_UNUSED
-#include "defs.h" // for Waypoint, fatal, route_head, le_read32, waypt_add, track_add_wpt, track_add_head, doing_rtes, doing_wpts, gb_color, route_add_head, route_add_wpt, unknown_alt, doing_trks
+#include "defs.h" // for Waypoint, gbFatal, route_head, le_read32, waypt_add, track_add_wpt, track_add_head, doing_rtes, doing_wpts, gb_color, route_add_head, route_add_wpt, unknown_alt, doing_trks
#include "gbfile.h" // for gbfread, gbfgetc, gbfgetint32, gbfreadbuf, gbfseek, gbfgetdbl, gbfgetint16, gbfclose, gbfgetnativecstr, gbfgetuint16, gbfopen_le
#include "jeeps/gpsmath.h" // for GPS_Math_Known_Datum_To_WGS84_M
-#define MYNAME "TPO"
-
-
/*******************************************************************************/
/* READ */
/*******************************************************************************/
/* check for the presence of a 3.0-style id string */
/* Note this check also finds version 4 id strings, e.g. "TOPO! Ver. 4.5.0" */
if (strncmp(v3_id_string, string_buffer, strlen(v3_id_string)) == 0) {
- /* fatal(MYNAME ": gpsbabel can only read TPO version 2.7.7 or below; this file is %s\n", string_buffer); */
+ /* gbFatal("gpsbabel can only read TPO version 2.7.7 or below; this file is %s\n", string_buffer); */
//fprintf(stderr,"gpsbabel can only read TPO version 2.7.7 or below; this file is %s\n", string_buffer);
gbfseek(tpo_file_in, -(string_size+1), SEEK_CUR);
while (true) {
if (gbfread(&byte, 1, 1, tpo_file_in) < 1) {
- fatal(MYNAME ": malformed input file - attempt to read past end");
+ gbFatal("malformed input file - attempt to read past end\n");
}
header_size++;
case 0xff: // 32-bit value
if constexpr(debug) {
- printf("Found 32-bit value indicator: %x\n", val);
+ gbDebug("Found 32-bit value indicator: %x\n", val);
}
return (gbfgetint32(tpo_file_in));
break;
case 0xfe: // 16-bit value
if constexpr(debug) {
- printf("Found 16-bit value indicator: %x\n", val);
+ gbDebug("Found 16-bit value indicator: %x\n", val);
}
return (gbfgetuint16(tpo_file_in));
break;
default: // 8-bit value
if constexpr(debug) {
- printf("Found 8-bit value: %x\n", val);
+ gbDebug("Found 8-bit value: %x\n", val);
}
return ((int)val);
break;
// Read record type
block_type = gbfgetint32(tpo_file_in);
if constexpr(debug) {
- printf("Block: %08x\tat offset: %08x\n", block_type, block_offset);
+ gbDebug("Block: %08x\tat offset: %08x\n", block_type, block_offset);
}
// Read offset to next record
constexpr int debug = 0; // 0-4 for increasingly verbose output in this subroutine)
if constexpr(debug) {
- printf("Processing Track Styles... (added in 2012 by SRE)\n");
+ gbDebug("Processing Track Styles... (added in 2012 by SRE)\n");
}
// Find block 0x050000 (definitions of styles for free-hand routes)
if (tpo_find_block(0x050000)) {
if constexpr(debug) {
- printf("Found no track styles, skipping tracks entirely\n");
+ gbDebug("Found no track styles, skipping tracks entirely\n");
}
return;
}
unsigned int track_style_count = tpo_read_int(); // 8 bit value
if constexpr(debug) {
- printf("Unpacking %u track styles...\n",track_style_count);
+ gbDebug("Unpacking %u track styles...\n",track_style_count);
}
QScopedArrayPointer<StyleInfo> styles(new StyleInfo[track_style_count]);
unsigned int skipped = (unsigned char) gbfgetc(tpo_file_in);
Q_UNUSED(skipped)
if constexpr(debug > 1) {
- printf("Skipping unknown byte 0x%x (? per-zoom-level visibility ?)\n", skipped);
+ gbDebug("Skipping unknown byte 0x%x (? per-zoom-level visibility ?)\n", skipped);
}
}
unsigned char tmp = gbfgetc(tpo_file_in);
Q_UNUSED(tmp)
if constexpr(debug > 2) {
- printf("Skipping unknown byte 0x%x after color (? always zero ?)\n",tmp);
+ gbDebug("Skipping unknown byte 0x%x after color (? always zero ?)\n",tmp);
}
// byte for track style name length, then name itself
tmp = gbfgetc(tpo_file_in);
// wrong byte order?? tmp = tpo_read_int(); // 16 bit value
if constexpr(debug > 1) {
- printf("Track style %u has %d-byte (0x%x) name\n", ii, tmp, tmp);
+ gbDebug("Track style %u has %d-byte (0x%x) name\n", ii, tmp, tmp);
}
if (tmp >= TRACKNAMELENGTH) {
- printf("ERROR! Found track style name over %d chars, skipping all tracks!\n",TRACKNAMELENGTH);
+ gbWarning("ERROR! Found track style name over %d chars, skipping all tracks!\n",TRACKNAMELENGTH);
return;
}
if (tmp) {
for (unsigned xx = 0; xx < 2; xx++) {
tmp = gbfgetc(tpo_file_in);
if constexpr(debug > 2) {
- printf("Skipping trailing line style byte 0x%x (? always zero ?)\n", tmp);
+ gbDebug("Skipping trailing line style byte 0x%x (? always zero ?)\n", tmp);
}
}
if constexpr(debug) {
- printf("Track style %u: color=#%02x%02x%02x, width=%d, dashed=%d, name=%s\n",
- ii, styles[ii].color[0], styles[ii].color[1], styles[ii].color[2], styles[ii].wide, styles[ii].dash, qPrintable(styles[ii].name));
+ gbDebug("Track style %u: color=#%02x%02x%02x, width=%d, dashed=%d, name=%s\n",
+ ii, styles[ii].color[0], styles[ii].color[1], styles[ii].color[2], styles[ii].wide, styles[ii].dash, gbLogCStr(styles[ii].name));
}
}
if constexpr(debug) {
- printf("Done Processing Track Styles... found %u styles\n", track_style_count);
+ gbDebug("Done Processing Track Styles... found %u styles\n", track_style_count);
}
// Find block 0x060000 (free-hand routes) (original track code, pre-2012, without styles)
if (tpo_find_block(0x060000)) {
if constexpr(debug) {
- printf("Found no track data block, skipping all tracks!\n");
+ gbDebug("Found no track data block, skipping all tracks!\n");
}
return;
}
unsigned int track_count = tpo_read_int();
if constexpr(debug) {
- printf("Number of tracks in file: %u\n", track_count);
+ gbDebug("Number of tracks in file: %u\n", track_count);
}
if (track_count == 0) {
if constexpr(debug) {
- printf("Found no track data, even though there was a track data block!\n");
+ gbDebug("Found no track data, even though there was a track data block!\n");
}
return;
}
//
for (unsigned ii = 0; ii < track_count; ii++) {
if constexpr(debug > 1) {
- printf("\nStarting Track %u",ii+1);
+ gbDebug("\nStarting Track %u",ii+1);
}
int lat = 0;
int lon = 0;
if (name_length) {
gbfread(track_name, 1, name_length, tpo_file_in);
if constexpr(debug > 2) {
- printf(", length %.0fm?, named %s\n", track_length, qPrintable(track_name));
+ gbDebug(", length %.0fm?, named %s\n", track_length, gbLogCStr(track_name));
}
} else { // Assign a generic track name
track_name = "TRK ";
track_name += QString::number(ii + 1);
if constexpr(debug > 2) {
- printf(", length %.0fm?, inventing name %s\n", track_length, qPrintable(track_name));
+ gbDebug(", length %.0fm?, inventing name %s\n", track_length, gbLogCStr(track_name));
}
}
track_temp->rte_name = track_name;
track_temp->line_width = styles[track_style].wide;
if constexpr(debug) {
- printf("Track Name: %s, ?Type?: %u, Style Name: %s, Width: %d, Dashed: %d, Color: #%s\n",
- qPrintable(track_name), line_type,
- qPrintable(styles[track_style].name),
+ gbDebug("Track Name: %s, ?Type?: %u, Style Name: %s, Width: %d, Dashed: %d, Color: #%s\n",
+ gbLogCStr(track_name), line_type,
+ gbLogCStr(styles[track_style].name),
styles[track_style].wide, styles[track_style].dash,
- qPrintable(rgb));
+ gbLogCStr(rgb));
}
// Track description
Waypoint* waypoint_temp;
#ifdef Tracks2012
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - byte %u, track %u, llvallid=%d\n",
+ gbDebug("%02x %02x %02x %02x - byte %u, track %u, llvallid=%d\n",
buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], jj, ii+1, llvalid);
}
// Time to read a new latlong?
lon = le_read32(&buf[jj]);
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - raw lon = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lon,jj);
+ gbDebug("%02x %02x %02x %02x - raw lon = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lon,jj);
}
jj+=4;
lat = le_read32(&buf[jj]);
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - raw lat = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lat,jj);
+ gbDebug("%02x %02x %02x %02x - raw lat = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lat,jj);
}
jj+=4;
lonscale = le_read32(&buf[jj]);
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - raw lon scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lonscale, jj);
+ gbDebug("%02x %02x %02x %02x - raw lon scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lonscale, jj);
}
//printf(" LONSCALE:");
//printf("%02x%02x%02x%02x", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3]);
latscale = le_read32(&buf[jj]);
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - raw lat scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], latscale, jj);
+ gbDebug("%02x %02x %02x %02x - raw lat scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], latscale, jj);
}
//printf(" LATSCALE:");
//printf("%02x%02x%02x%02x ", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3]);
track_add_wpt(track_temp, waypoint_temp);
cnttp++;
if constexpr(debug > 3) {
- printf("Adding BASIC trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude);
+ gbDebug("Adding BASIC trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude);
}
}
#else
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x = bytes %u-%u (track %u, mode now %s)\n",
+ gbDebug("%02x %02x %02x %02x = bytes %u-%u (track %u, mode now %s)\n",
buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], jj, jj+3, ii+1, tpmodeshow[tpmode]);
}
if (tpmode == GetFullPoint) {
lon = le_read32(&buf[jj]);
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - raw lon = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lon,jj);
+ gbDebug("%02x %02x %02x %02x - raw lon = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lon,jj);
}
jj+=4;
lat = le_read32(&buf[jj]);
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - raw lat = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lat,jj);
+ gbDebug("%02x %02x %02x %02x - raw lat = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lat,jj);
}
jj+=4;
track_add_wpt(track_temp, waypoint_temp);
cnttp++;
if (((abs(waypoint_temp->latitude - lastlat) > 1.0) && lastlat) || ((abs(waypoint_temp->longitude - lastlon) > 1.0) && lastlon)) {
- printf("WARNING! Track '%s' point #%d is more than 1 degree from the last track point!\n (probably corrupt - try splitting in two at sharp corners)\n", qPrintable(track_name), cnttp);
+ gbWarning("WARNING! Track '%s' point #%d is more than 1 degree from the last track point!\n (probably corrupt - try splitting in two at sharp corners)\n", gbLogCStr(track_name), cnttp);
}
lastlat = waypoint_temp->latitude;
lastlon = waypoint_temp->longitude;
if constexpr(debug > 3) {
- printf("Adding BASIC trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude);
+ gbDebug("Adding BASIC trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude);
}
// after full point, can have scaling or 0x88 for another full point or single byte to be scaled
if ((jj+3<track_byte_count) && !(buf[jj+3]) && !(buf[jj+2])) {
lonscale = le_read32(&buf[jj]);
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - raw lon scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lonscale, jj);
+ gbDebug("%02x %02x %02x %02x - raw lon scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], lonscale, jj);
}
jj+=4;
tpmode = CheckLatScale;
if ((jj+3<track_byte_count) && !(buf[jj+3]) && !(buf[jj+2])) {
latscale = le_read32(&buf[jj]);
if constexpr(debug > 3) {
- printf("%02x %02x %02x %02x - raw lat scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], latscale, jj);
+ gbDebug("%02x %02x %02x %02x - raw lat scale = %d (byte %u)\n", buf[jj], buf[jj+1], buf[jj+2], buf[jj+3], latscale, jj);
}
jj+=4;
}
// offsets.
else if (buf[jj] == 0x88) {
if constexpr(debug > 3) {
- printf("%02x should mean full lat/lon comes next (byte %u)\n",buf[jj],jj);
+ gbDebug("%02x should mean full lat/lon comes next (byte %u)\n",buf[jj],jj);
}
jj++;
llvalid = 0;
if (tpmode == Check0x88Tag) {
if (buf[jj] == FullPointTag) {
if constexpr(debug > 3) {
- printf("%02x should mean full lat/lon comes next (byte %u)\n",buf[jj],jj);
+ gbDebug("%02x should mean full lat/lon comes next (byte %u)\n",buf[jj],jj);
}
jj++;
tpmode = GetFullPoint;
// combo embedded in this track next.
else if (buf[jj] == 0x00) {
if constexpr(debug > 3) {
- printf("%02x should mean full lat/lon or lonscale/latscale comes next (at byte %u)\n",buf[jj],jj);
+ gbDebug("%02x should mean full lat/lon or lonscale/latscale comes next (at byte %u)\n",buf[jj],jj);
}
//printf(" ZERO ");
jj++;
else {
static const int scarray[] = {0,1,2,3,4,5,6,7,-8,-7,-6,-5,-4,-3,-2,-1};
if constexpr(debug) {
- printf("%02x - lat mult = %d, lon mult=%d, byte %u\n", buf[jj], scarray[buf[jj] & 0xf], scarray[buf[jj] >> 4], jj);
+ gbDebug("%02x - lat mult = %d, lon mult=%d, byte %u\n", buf[jj], scarray[buf[jj] & 0xf], scarray[buf[jj] >> 4], jj);
}
if (buf[jj] == 0) {
- fatal(MYNAME ": Found unexpected ZERO\n");
+ gbFatal("Found unexpected ZERO\n");
}
if (latscale == 0 || lonscale == 0) {
- fatal(MYNAME ": Found bad scales lonscale=0x%x latscale=0x%x\n", lonscale, latscale);
+ gbFatal("Found bad scales lonscale=0x%x latscale=0x%x\n", lonscale, latscale);
}
if constexpr(debug > 3) {
- printf("%02x - adjusting prev lat/lon from %i/%i", buf[jj], lat, lon);
+ gbDebug("%02x - adjusting prev lat/lon from %i/%i", buf[jj], lat, lon);
}
lon += lonscale * scarray[buf[jj] >> 4];
lat += latscale * scarray[(buf[jj] & 0xf)];
if constexpr(debug > 3) {
- printf(" to %i/%i, byte %u\n", lat, lon, jj);
+ gbDebug(" to %i/%i, byte %u\n", lat, lon, jj);
}
//printf(".");
jj++;
track_add_wpt(track_temp, waypoint_temp);
cnttp++;
if constexpr(debug > 3) {
- printf("Adding ADJUSTED trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude);
+ gbDebug("Adding ADJUSTED trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude);
}
}
#else
// list of single bytes to be scaled can only end with 0x00, can then have full point or scaling
if (buf[jj] == EndScaleTag) {
if constexpr(debug > 3) {
- printf("%02x should mean full lat/lon or lonscale/latscale comes next (at byte %u)\n",buf[jj],jj);
+ gbDebug("%02x should mean full lat/lon or lonscale/latscale comes next (at byte %u)\n",buf[jj],jj);
}
jj++;
tpmode = GetFullPoint;
if (buf[jj] == FullPointTag) {
if constexpr(debug > 3) {
- printf("%02x should mean full lat/lon comes next (at byte %u)\n",buf[jj],jj);
+ gbDebug("%02x should mean full lat/lon comes next (at byte %u)\n",buf[jj],jj);
}
jj++;
tpmode = GetFullPoint;
static const int scarray[] = {0,1,2,3,4,5,6,7,-8,-7,-6,-5,-4,-3,-2,-1}; // MAGIC! (no idea where this comes from)
if constexpr(debug) {
- printf("%02x - lat mult = %d, lon mult=%d, byte %u\n", buf[jj], scarray[buf[jj] & 0xf], scarray[buf[jj] >> 4], jj);
+ gbDebug("%02x - lat mult = %d, lon mult=%d, byte %u\n", buf[jj], scarray[buf[jj] & 0xf], scarray[buf[jj] >> 4], jj);
}
if (buf[jj] == 0) {
- fatal(MYNAME ": Found unexpected ZERO\n");
+ gbFatal("Found unexpected ZERO\n");
}
if ((latscale == 0) || (lonscale == 0)) {
- fatal(MYNAME ": Found bad scales lonscale=0x%x latscale=0x%x while trying to scale a single byte trackpoint\n", lonscale, latscale);
+ gbFatal("Found bad scales lonscale=0x%x latscale=0x%x while trying to scale a single byte trackpoint\n", lonscale, latscale);
}
if constexpr(debug > 3) {
- printf("%02x - adjusting prev lat/lon from %i/%i", buf[jj], lat, lon);
+ gbDebug("%02x - adjusting prev lat/lon from %i/%i", buf[jj], lat, lon);
}
lon += lonscale * scarray[buf[jj] >> 4];
lat += latscale * scarray[(buf[jj] & 0xf)];
if constexpr(debug > 3) {
- printf(" to %i/%i, byte %u\n", lat, lon, jj);
+ gbDebug(" to %i/%i, byte %u\n", lat, lon, jj);
}
jj++;
track_add_wpt(track_temp, waypoint_temp);
cnttp++;
if constexpr(debug > 3) {
- printf("Adding ADJUSTED trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude);
+ gbDebug("Adding ADJUSTED trackpoint #%i: lat=%.5f, lon=%.5f\n", cnttp, waypoint_temp->latitude, waypoint_temp->longitude);
}
if (((abs(waypoint_temp->latitude - lastlat) > 1) && lastlat) || ((abs(waypoint_temp->longitude - lastlon) > 1) && lastlon)) {
- printf("WARNING! Track '%s' point #%i is more than 1 degree from the last track point!\n (probably corrupt - try splitting in two at sharp corners)\n", qPrintable(track_name), cnttp);
+ gbWarning("WARNING! Track '%s' point #%i is more than 1 degree from the last track point!\n (probably corrupt - try splitting in two at sharp corners)\n", gbLogCStr(track_name), cnttp);
}
lastlat = waypoint_temp->latitude;
lastlon = waypoint_temp->longitude;
void
TpoFormatBase::tpo_rd_init(const QString& fname)
{
- tpo_file_in = gbfopen_le(fname, "rb", MYNAME);
+ tpo_file_in = gbfopen_le(fname, "rb");
tpo_check_version_string();
if (tpo_version == 2.0) {
if (doing_wpts || doing_rtes) {
- fatal(MYNAME ": this file format only supports tracks, not waypoints or routes.\n");
+ gbFatal("this file format only supports tracks, not waypoints or routes.\n");
}
/*fprintf(stderr,"Version 2.x, Looking for CTopoRoute\n"); */
* plus four bytes is the end of the embedded PNG image */
tpo_read_until_section("Red Without Arrow", 17);
} else {
- fatal(MYNAME ": gpsbabel can only read TPO versions through 3.x.x\n");
+ gbFatal("gpsbabel can only read TPO versions through 3.x.x\n");
}
}
//printf("\nFound a version 3.x file\n");
tpo_read_3_x();
} else {
- fatal(MYNAME ": gpsbabel can only read TPO versions through 3.x.x\n");
+ gbFatal("gpsbabel can only read TPO versions through 3.x.x\n");
}
}
#include <algorithm> // for_each, sort, stable_sort
#include <cassert> // for assert
#include <cmath> // for nan
-#include <cstdio> // for printf
#include <cstdlib> // for abs
#include <ctime> // for gmtime, strftime, time_t, tm
#include <iterator> // for next
#if FILTERS_ENABLED || MINIMAL_FILTERS
-#define MYNAME "trackfilter"
/*******************************************************************************
* helpers
bool ok;
qint64 partial = match.captured(idx).toLong(&ok);
if (!ok) {
- fatal(MYNAME "-time: invalid quantity in move option \"%s\"!\n", qPrintable(match.captured(idx)));
+ gbFatal("time: invalid quantity in move option \"%s\"!\n", gbLogCStr(match.captured(idx)));
}
switch (match.captured(idx+1).at(0).toLower().toLatin1()) {
case 'z':
break;
default:
- fatal(MYNAME "-time: invalid unit in move option \"%s\"!\n", qPrintable(match.captured(idx+1)));
+ gbFatal("time: invalid unit in move option \"%s\"!\n", gbLogCStr(match.captured(idx+1)));
}
result += partial;
}
if constexpr(TRACKF_DBG) {
- qDebug() << MYNAME "-time option: shift =" << result / 1000.0 << "seconds";
+ qDebug() << "time option: shift =" << result / 1000.0 << "seconds";
}
} else {
- fatal(MYNAME "-time: invalid value in move option \"%s\"!\n", qPrintable(arg));
+ gbFatal("time: invalid value in move option \"%s\"!\n", gbLogCStr(arg));
}
return result;
*nsats = 0;
return fix_none;
}
- fatal(MYNAME ": invalid fix type\n");
+ gbFatal("invalid fix type\n");
return fix_unknown;
}
QRegularExpression regex(QRegularExpression::wildcardToRegularExpression(opt_name),
QRegularExpression::CaseInsensitiveOption);
if (!regex.isValid()) {
- fatal(FatalMsg() << "track: name option is an invalid expression.");
+ gbFatal(FatalMsg() << "track: name option is an invalid expression.");
}
if (!regex.match(track->rte_name).hasMatch()) {
track_del_head(const_cast<route_head*>(track));
foreach (const Waypoint* wpt, track->waypoint_list) {
if (!(opt_merge && opt_discard) && need_time && (!wpt->creation_time.isValid())) {
- fatal(MYNAME "-init: Found track point at %f,%f without time!\n",
+ gbFatal("init: Found track point at %f,%f without time!\n",
wpt->latitude, wpt->longitude);
}
if (!opt_merge) {
QString t1 = prev->CreationTimeXML();
QString t2 = wpt->CreationTimeXML();
- fatal(MYNAME "-init: Track points badly ordered (timestamp %s > %s)!\n", qPrintable(t1), qPrintable(t2));
+ gbFatal("init: Track points badly ordered (timestamp %s > %s)!\n", gbLogCStr(t1), gbLogCStr(t2));
}
}
prev = wpt;
}
if (opt_title.isEmpty()) {
- fatal(MYNAME "-title: Missing your title!\n");
+ gbFatal("title: Missing your title!\n");
}
for (auto* track : std::as_const(track_list)) {
trackfilter_pack_init_rte_name(track, QDateTime::fromMSecsSinceEpoch(0, QtUTC));
auto prev_last_time = trackfilter_get_last_time(track_list.at(j));
auto curr_first_time = trackfilter_get_first_time(track_list.at(i));
if (prev_last_time >= curr_first_time) {
- fatal(MYNAME "-pack: Tracks overlap in time! %s >= %s at %d\n",
- qPrintable(prev_last_time.toString()),
- qPrintable(curr_first_time.toString()), i);
+ gbFatal("pack: Tracks overlap in time! %s >= %s at %d\n",
+ gbLogCStr(prev_last_time.toString()),
+ gbLogCStr(curr_first_time.toString()), i);
}
}
}
if (global_opts.verbose_status > 0) {
- printf(MYNAME "-merge: %d track point(s) merged, %d dropped.\n", track_waypt_count(), original_waypt_count - track_waypt_count());
+ gbInfo("merge: %d track point(s) merged, %d dropped.\n", track_waypt_count(), original_waypt_count - track_waypt_count());
}
if ((original_waypt_count > 0) && (track_waypt_count() == 0)) {
- warning(MYNAME "-merge: All %d track points have been dropped!\n", original_waypt_count);
+ gbWarning("merge: All %d track points have been dropped!\n", original_waypt_count);
}
}
}
void TrackFilter::trackfilter_split()
{
if (track_list.size() > 1) {
- fatal(MYNAME "-split: Cannot split more than one track, please pack (or merge) before!\n");
+ gbFatal("split: Cannot split more than one track, please pack (or merge) before!\n");
} else if (!track_list.isEmpty()) {
route_head* master = track_list.first();
if (master->rte_waypt_ct() <= 1) {
bool ok;
interval = match.captured(1).toDouble(&ok);
if (!ok || interval <= 0.0) {
- fatal(MYNAME ": invalid time interval specified \"%s\", must be a positive number.\n", qPrintable(match.captured(1)));
+ gbFatal("invalid time interval specified \"%s\", must be a positive number.\n", gbLogCStr(match.captured(1)));
}
switch (match.captured(2).at(0).toLower().toLatin1()) {
case 's':
break;
default:
- fatal(MYNAME ": invalid time interval unit specified.\n");
+ gbFatal("invalid time interval unit specified.\n");
}
if constexpr(TRACKF_DBG) {
- printf(MYNAME ": interval %f seconds\n", interval);
+ gbDebug("interval %f seconds\n", interval);
}
} else {
- fatal(MYNAME ": invalid timer interval specified \"%s\", must be a positive number, followed by 'd' for days, 'h' for hours, 'm' for minutes or 's' for seconds.\n", qPrintable(opt_split));
+ gbFatal("invalid timer interval specified \"%s\", must be a positive number, followed by 'd' for days, 'h' for hours, 'm' for minutes or 's' for seconds.\n", gbLogCStr(opt_split));
}
}
bool ok;
distance = match.captured(1).toDouble(&ok);
if (!ok || distance <= 0.0) {
- fatal(MYNAME ": invalid time distance specified \"%s\", must be a positive number.\n", qPrintable(match.captured(1)));
+ gbFatal("invalid time distance specified \"%s\", must be a positive number.\n", gbLogCStr(match.captured(1)));
}
switch (match.captured(2).at(0).toLower().toLatin1()) {
distance *= kMetersPerMile;
break;
default:
- fatal(MYNAME ": invalid distance unit specified.\n");
+ gbFatal("invalid distance unit specified.\n");
}
if constexpr(TRACKF_DBG) {
- printf(MYNAME ": distance %f meters\n", distance);
+ gbDebug("distance %f meters\n", distance);
}
} else {
- fatal(MYNAME ": invalid distance specified \"%s\", must be a positive number followed by 'k' for kilometers or 'm' for miles.\n", qPrintable(opt_sdistance.get()));
+ gbFatal("invalid distance specified \"%s\", must be a positive number followed by 'k' for kilometers or 'm' for miles.\n", gbLogCStr(opt_sdistance.get()));
}
}
wpt->GetCreationTime().toLocalTime().date();
if constexpr(TRACKF_DBG) {
if (new_track_flag) {
- printf(MYNAME ": new day %s\n", qPrintable(wpt->GetCreationTime().toLocalTime().date().toString(Qt::ISODate)));
+ gbDebug("new day %s\n", gbLogCStr(wpt->GetCreationTime().toLocalTime().date().toString(Qt::ISODate)));
}
}
} else {
if (curdist <= distance) {
new_track_flag = false;
} else if constexpr(TRACKF_DBG) {
- printf(MYNAME ": sdistance, %g > %g\n", curdist, distance);
+ gbDebug("sdistance, %g > %g\n", curdist, distance);
}
}
if (tr_interval <= interval) {
new_track_flag = false;
} else if constexpr(TRACKF_DBG) {
- printf(MYNAME ": split, %g > %g\n", tr_interval, interval);
+ gbDebug("split, %g > %g\n", tr_interval, interval);
}
}
}
if (new_track_flag) {
if constexpr(TRACKF_DBG) {
- printf(MYNAME ": splitting new track\n");
+ gbDebug("splitting new track\n");
}
curr = new route_head;
trackfilter_split_init_rte_name(curr, wpt->GetCreationTime());
}
}
if (timeless_points > 0) {
- warning(MYNAME "-move: %d points out of %d total points didn't have "
+ gbWarning("move: %d points out of %d total points didn't have "
"time information and could not be moved.\n",
timeless_points, track_waypt_count());
}
result.setTimeSpec(Qt::UTC);
#endif
if (!result.isValid()) {
- fatal(MYNAME "-range-check: Invalid timestamp \"%s\"!\n", qPrintable(timestr));
+ gbFatal("range-check: Invalid timestamp \"%s\"!\n", gbLogCStr(timestr));
}
if constexpr(TRACKF_DBG) {
- qDebug() << MYNAME "-range-check: " << result;
+ qDebug() << "range-check: " << result;
}
} else {
- fatal(MYNAME "-range-check: Invalid value for option \"%s\"!\n", qPrintable(timestr));
+ gbFatal("range-check: Invalid value for option \"%s\"!\n", gbLogCStr(timestr));
}
return result;
}
if ((original_waypt_count > 0) && (track_waypt_count() == 0)) {
- warning(MYNAME "-range: All %d track points have been dropped!\n", original_waypt_count);
+ gbWarning("range: All %d track points have been dropped!\n", original_waypt_count);
}
}
result.start.setTimeSpec(Qt::UTC);
#endif
if (!result.start.isValid()) {
- fatal(MYNAME "-faketime-check: Invalid timestamp \"%s\"!\n", qPrintable(start));
+ gbFatal("faketime-check: Invalid timestamp \"%s\"!\n", gbLogCStr(start));
}
if (match.capturedLength(3) > 0) {
bool ok;
result.step = llround(1000.0 * match.captured(3).toDouble(&ok));
if (!ok) {
- fatal(MYNAME "-faketime-check: Invalid step \"%s\"!\n", qPrintable(match.captured(3)));
+ gbFatal("faketime-check: Invalid step \"%s\"!\n", gbLogCStr(match.captured(3)));
}
} else {
result.step = 0;
}
if constexpr(TRACKF_DBG) {
- qDebug() << MYNAME "-faketime option: force =" << result.force << ", timestamp =" << result.start << ", step =" << result.step << "milliseconds";
+ qDebug() << "faketime option: force =" << result.force << ", timestamp =" << result.start << ", step =" << result.step << "milliseconds";
}
} else {
- fatal(MYNAME "-faketime-check: Invalid value for faketime option \"%s\"!\n", qPrintable(timestr));
+ gbFatal("faketime-check: Invalid value for faketime option \"%s\"!\n", gbLogCStr(timestr));
}
return result;
if (opt_minpoints) {
minimum_points = opt_minpoints.get_result();
if (minimum_points <= 0) {
- fatal(MYNAME "-minimum_points: option value must be a positive integer!\n");
+ gbFatal("minimum_points: option value must be a positive integer!\n");
}
track_disp_all(trackfilter_minpoint_list_cb_f, nullptr, nullptr);
}
#if FILTERS_ENABLED
-#define MYNAME "transform"
-
void TransformFilter::transform_waypoints()
{
auto* rte = new route_head;
route_flush_all_tracks();
}
} else {
- fatal(MYNAME ": Invalid option value (%s)!\n", qPrintable(opt_waypts));
+ gbFatal("Invalid option value (%s)!\n", gbLogCStr(opt_waypts));
}
}
if (opt_routes) {
route_flush_all_tracks();
}
} else {
- fatal(MYNAME ": Invalid option value (%s)!\n", qPrintable(opt_routes));
+ gbFatal("Invalid option value (%s)!\n", gbLogCStr(opt_routes));
}
}
if (opt_tracks) {
route_flush_all_routes();
}
} else {
- fatal(MYNAME ": Invalid option value (%s)!\n", qPrintable(opt_tracks));
+ gbFatal("Invalid option value (%s)!\n", gbLogCStr(opt_tracks));
}
}
}
#include "src/core/textstream.h" // for TextStream
-#define MYNAME "unicsv"
-
/*
* ! Please use always underscores in field names !
* we check a second time after replacing underscores with spaces
*consumed = 0; /* for a possible date */
return {};
}
- fatal(FatalMsg() << MYNAME << ": Could not parse date string (" << str << ").");
+ gbFatal(FatalMsg() << "Could not parse date string (" << str << ").");
}
if ((p1 > 99) || (sep[0] == '-')) { /* Y-M-D (iso like) */
*consumed = 0;
return {}; /* don't stop here */
}
- fatal(FatalMsg() << MYNAME << ": Could not parse date string (" << str << ").");
+ gbFatal(FatalMsg() << "Could not parse date string (" << str << ").");
}
QDate result{tm.tm_year, tm.tm_mon, tm.tm_mday};
if (!result.isValid()) {
- fatal(FatalMsg() << MYNAME << ": Invalid date parsed from string (" << str << ").");
+ gbFatal(FatalMsg() << "Invalid date parsed from string (" << str << ").");
}
return result;
}
}
int ct = sscanf(str, "%d%*1[.://]%d%*1[.://]%d%lf", &hour, &min, &sec, &frac_sec);
if (ct < 3) {
- fatal(FatalMsg() << MYNAME << ": Could not parse time string (" << str << ").");
+ gbFatal(FatalMsg() << "Could not parse time string (" << str << ").");
}
if (ct >= 4) {
// Don't round up and ripple through seconds, minutes, hours.
QTime result{hour, min, sec, msec};
if (!result.isValid()) {
- fatal(FatalMsg() << MYNAME << ": Invalid time parsed from string (" << str << ").");
+ gbFatal(FatalMsg() << "Invalid time parsed from string (" << str << ").");
}
return result;
}
if (it == fields_def.cend()) { // not found
if (global_opts.debug_level) {
- warning(MYNAME ": Unhandled column \"%s\".\n", qPrintable(value));
+ gbWarning("Unhandled column \"%s\".\n", gbLogCStr(value));
}
} else { // found
const field_t f = *it;
unicsv_fields_tab.last() = f.type;
if (global_opts.debug_level) {
- warning(MYNAME ": Interpreting column \"%s\" as %s(%d).\n", qPrintable(value), qPrintable(f.name), f.type);
+ gbWarning("Interpreting column \"%s\" as %s(%d).\n", gbLogCStr(value), gbLogCStr(f.name), f.type);
}
/* handle some special items */
unicsv_detect = (!(global_opts.masked_objective & (WPTDATAMASK | TRKDATAMASK | RTEDATAMASK | POSNDATAMASK)));
unicsv_track = unicsv_route = nullptr;
- unicsv_datum_idx = gt_lookup_datum_index(opt_datum, MYNAME);
+ unicsv_datum_idx = gt_lookup_datum_index(opt_datum);
fin = new gpsbabel::TextStream;
- fin->open(fname, QIODevice::ReadOnly, MYNAME, opt_codec.get().toUtf8());
+ fin->open(fname, QIODevice::ReadOnly, opt_codec.get().toUtf8());
unicsv_lineno = 0;
if (opt_fields) {
QString fields = opt_fields;
break;
case fld_altitude:
- if (parse_distance(value, &d, unicsv_altscale, MYNAME)) {
+ if (parse_distance(value, &d, unicsv_altscale)) {
if (fabs(d) < fabs(unknown_alt)) {
wpt->altitude = d;
}
case fld_utm:
parse_coordinates(value, unicsv_datum_idx, grid_utm,
- &wpt->latitude, &wpt->longitude, MYNAME);
+ &wpt->latitude, &wpt->longitude);
/* coordinates from parse_coordinates are in WGS84
don't convert a second time */
src_datum = kDatumWGS84;
case fld_bng:
parse_coordinates(value, kDatumOSGB36, grid_bng,
- &wpt->latitude, &wpt->longitude, MYNAME);
+ &wpt->latitude, &wpt->longitude);
/* coordinates from parse_coordinates are in WGS84
don't convert a second time */
src_datum = kDatumWGS84;
case fld_swiss:
parse_coordinates(value, kDatumWGS84, grid_swiss,
- &wpt->latitude, &wpt->longitude, MYNAME);
+ &wpt->latitude, &wpt->longitude);
/* coordinates from parse_coordinates are in WGS84
don't convert a second time */
src_datum = kDatumWGS84;
break;
case fld_speed:
- if (parse_speed(value, &d, 1.0, MYNAME)) {
+ if (parse_speed(value, &d, 1.0)) {
wpt->set_speed(d);
if (unicsv_detect) {
unicsv_data_type = trkdata;
break;
case fld_proximity:
- if (parse_distance(value, &d, unicsv_proximityscale, MYNAME)) {
+ if (parse_distance(value, &d, unicsv_proximityscale)) {
wpt->set_proximity(d);
}
break;
case fld_depth:
- if (parse_distance(value, &d, unicsv_depthscale, MYNAME)) {
+ if (parse_distance(value, &d, unicsv_depthscale)) {
wpt->set_depth(d);
}
break;
if (! GPS_Math_EN_To_UKOSNG_Map(
bng_easting, bng_northing,
&bnge, &bngn, bngz)) {
- fatal(MYNAME ": Unable to convert BNG coordinates (%.f %.f)!\n",
+ gbFatal("Unable to convert BNG coordinates (%.f %.f)!\n",
bng_easting, bng_northing);
}
if (! GPS_Math_UKOSMap_To_WGS84_H(
bngz, bnge, bngn,
&wpt->latitude, &wpt->longitude))
- fatal(MYNAME ": Unable to convert BNG coordinates (%s %.f %.f)!\n",
+ gbFatal("Unable to convert BNG coordinates (%s %.f %.f)!\n",
bngz, bnge, bngn);
} else { // traditional zone easting northing
if (! GPS_Math_UKOSMap_To_WGS84_H(
CSTR(bng_zone), bng_easting, bng_northing,
&wpt->latitude, &wpt->longitude))
- fatal(MYNAME ": Unable to convert BNG coordinates (%s %.f %.f)!\n",
+ gbFatal("Unable to convert BNG coordinates (%s %.f %.f)!\n",
CSTR(bng_zone), bng_easting, bng_northing);
}
src_datum = kDatumWGS84; /* don't convert afterwards */
[[noreturn]] void UnicsvFormat::unicsv_fatal_outside(const Waypoint* wpt) const
{
*fout << "#####\n";
- fatal(MYNAME ": %s (%s) is outside of convertible area of grid \"%s\"!\n",
- wpt->shortname.isEmpty() ? "Waypoint" : qPrintable(wpt->shortname),
- qPrintable(pretty_deg_format(wpt->latitude, wpt->longitude, 'd', nullptr, false)),
- qPrintable(gt_get_mps_grid_longname(unicsv_grid_idx, MYNAME)));
+ gbFatal("%s (%s) is outside of convertible area of grid \"%s\"!\n",
+ wpt->shortname.isEmpty() ? "Waypoint" : gbLogCStr(wpt->shortname),
+ gbLogCStr(pretty_deg_format(wpt->latitude, wpt->longitude, 'd', nullptr, false)),
+ gbLogCStr(gt_get_mps_grid_longname(unicsv_grid_idx)));
}
void
UnicsvFormat::wr_init(const QString& fname)
{
if (opt_fields) {
- fatal(FatalMsg() << MYNAME <<
- ": option 'fields' is not supported on output");
+ gbFatal(FatalMsg() <<
+ "option 'fields' is not supported on output");
}
fout = new gpsbabel::TextStream;
- fout->open(fname, QIODevice::WriteOnly, MYNAME, opt_codec.get().toUtf8());
+ fout->open(fname, QIODevice::WriteOnly, opt_codec.get().toUtf8());
fout->setRealNumberNotation(QTextStream::FixedNotation);
unicsv_outp_flags.reset();
if (int i = opt_grid.toInt(&ok); ok) {
unicsv_grid_idx = (grid_type) i;
if ((unicsv_grid_idx < GRID_INDEX_MIN) || (unicsv_grid_idx > GRID_INDEX_MAX))
- fatal(MYNAME ": Grid index out of range (%d..%d)!\n",
+ gbFatal("Grid index out of range (%d..%d)!\n",
(int)GRID_INDEX_MIN, (int)GRID_INDEX_MAX);
} else {
- unicsv_grid_idx = gt_lookup_grid_type(opt_grid, MYNAME);
+ unicsv_grid_idx = gt_lookup_grid_type(opt_grid);
}
}
{
unicsv_datum_idx = kDatumWGS84; /* internal, becomes CH1903 */
} else {
- unicsv_datum_idx = gt_lookup_datum_index(opt_datum, MYNAME);
+ unicsv_datum_idx = gt_lookup_datum_index(opt_datum);
}
llprec = opt_prec.get_result();
UnicsvFormat::unicsv_check_modes(bool test)
{
if (test) {
- fatal(FatalMsg() << MYNAME <<
- " : Invalid combination of -w, -t, -r selected. Use only one.");
+ gbFatal(FatalMsg() <<
+ "Invalid combination of -w, -t, -r selected. Use only one.");
}
}
route_disp_all(nullptr, nullptr, unicsv_waypt_enum_cb_lambda);
break;
case posndata:
- fatal(FatalMsg() << MYNAME << ": Realtime positioning not supported.");
+ gbFatal(FatalMsg() << "Realtime positioning not supported.");
}
*fout << "No" << unicsv_fieldsep;
units = u;
break;
default:
- fatal("not done yet");
+ gbFatal("not done yet\n");
break;
}
}
break;
default:
- fatal("not done yet");
+ gbFatal("not done yet\n");
break;
}
break;
default:
- fatal("not done yet");
+ gbFatal("not done yet\n");
break;
}
}
break;
default:
- fatal("not done yet");
+ gbFatal("not done yet\n");
}
return {d, tag};
void* obj = malloc(size);
if (!obj) {
- fatal("gpsbabel: Unable to allocate %zu bytes of memory.\n", size);
+ gbFatal("gpsbabel: Unable to allocate %zu bytes of memory.\n", size);
}
return obj;
void* obj = calloc(nmemb, size);
if (!obj) {
- fatal("gpsbabel: Unable to allocate %zu units of %zu bytes of memory.\n", nmemb, size);
+ gbFatal("gpsbabel: Unable to allocate %zu units of %zu bytes of memory.\n", nmemb, size);
}
return obj;
char* o = s ? strdup(s) : strdup("");
if (!o) {
- fatal("gpsbabel: Unable to allocate %zu bytes of memory.\n", strlen(s));
+ gbFatal("gpsbabel: Unable to allocate %zu bytes of memory.\n", strlen(s));
}
return o;
char* o = (char*) realloc(p, s);
if (!o) {
- fatal("gpsbabel: Unable to realloc %zu bytes of memory.\n", s);
+ gbFatal("gpsbabel: Unable to realloc %zu bytes of memory.\n", s);
}
return o;
* Wrapper for open that honours - for stdin, stdout, unifies error text.
*/
FILE*
-xfopen(const QString& fname, const char* type, const QString& errtxt)
+xfopen(const QString& fname, const char* type)
{
bool am_writing = strchr(type, 'w') != nullptr;
if (fname.isEmpty()) {
- fatal("%s must have a filename specified for %s.\n",
- qPrintable(errtxt), am_writing ? "write" : "read");
+ gbFatal("must have a filename specified for %s.\n",
+ am_writing ? "write" : "read");
}
if (fname == "-") {
// vs. the STD C library used for the actual file I/O. It's worth it
// to get a better error message.
QFileInfo info(fname);
- fatal("%s cannot open '%s' for %s. Error was '%s'.\n",
- qPrintable(errtxt), qPrintable(info.absoluteFilePath()),
+ gbFatal("cannot open '%s' for %s. Error was '%s'.\n",
+ gbLogCStr(info.absoluteFilePath()),
am_writing ? "write" : "read",
strerror(errno));
}
}
if (!okay) {
- fatal(FatalMsg().nospace() << "Invalid character " << cin << " in date format " << human_datef << "!");
+ gbFatal(FatalMsg().nospace() << "Invalid character " << cin << " in date format " << human_datef << "!");
}
}
return result;
}
if (!okay) {
- fatal(FatalMsg().nospace() << "Invalid character " << cin << " in time format " << human_timef << "!");
+ gbFatal(FatalMsg().nospace() << "Invalid character " << cin << " in time format " << human_timef << "!");
}
}
return result;
{
QTextCodec* codec = QTextCodec::codecForName(cs_name);
if (codec == nullptr) {
- fatal(FatalMsg().nospace() << "Unsupported character set " << cs_name << ".");
+ gbFatal(FatalMsg().nospace() << "Unsupported character set " << cs_name << ".");
}
return codec;
}
#include <cassert> // for assert
#include <cstdarg> // for va_end, va_start
-#include <cstdio> // for fclose, fgets, fread, vfprintf, stderr, va_list
+#include <cstdio> // for fclose, fgets, fread, va_list
#include <cstdlib> // for strtod
#include <cstring> // for strncmp, strcat, strcpy, strstr
void
V900Format::v900_log(const char* fmt, ...)
{
- va_list ap;
-
- if (global_opts.debug_level < 1) {
- return;
+ if (global_opts.debug_level >= 1) {
+ va_list ap;
+ va_start(ap, fmt);
+ gbVLegacyLog(QtDebugMsg, fmt, ap);
+ va_end(ap);
}
-
- va_start(ap, fmt);
- vfprintf(stderr, fmt, ap);
- va_end(ap);
}
void
V900Format::rd_init(const QString& fname)
{
- v900_log("%s(%s)\n",__func__,qPrintable(fname));
+ v900_log("%s(%s)\n",__func__,gbLogCStr(fname));
/* note: file is opened in binary mode, since lines end with \r\n, and in windows text mode
that will be translated to a single \n, making the line len one character shorter than
on linux machines.
*/
fin = ufopen(fname, "rb");
if (!fin) {
- fatal("v900: could not open '%s'.\n", qPrintable(fname));
+ gbFatal("v900: could not open '%s'.\n", gbLogCStr(fname));
}
}
/* first, determine if this is advanced mode by reading the first line.
since the first line does not contain any nulls, it can be safely read by fgets(). */
if (!fgets(line.text, sizeof(line), fin)) {
- fatal("v900: error reading header (first) line from input file\n");
+ gbFatal("v900: error reading header (first) line from input file\n");
}
int is_advanced_mode = (nullptr != strstr(line.text,"PDOP")); /* PDOP field appears only in advanced mode */
bad |= (line.bas.common.comma9 != ',');
if (bad) {
- warning("v900: skipping malformed record at line %d\n", lc);
+ gbWarning("v900: skipping malformed record at line %d\n", lc);
}
line.bas.common.comma1 = 0;
/* change all "," characters to NULLs.
so every field is null terminated.
*/
- assert(line.adv.comma10==','); // TODO: abort with fatal()
+ assert(line.adv.comma10==','); // TODO: abort with gbFatal()
assert(line.adv.comma11==',');
assert(line.adv.comma12==',');
assert(line.adv.comma13==',');
#include "defs.h"
#include "validate.h"
-#include <cstdio>
#if FILTERS_ENABLED
-#define MYNAME "validate"
void ValidateFilter::validate_head(const route_head* /*unused*/)
{
{
total_point_ct += point_ct;
total_segment_ct += segment_ct;
- if (debug) {
- fprintf(stderr, "%s %d ct: %d, waypt_count: %d, segments %d\n", segment_type, header->rte_num, point_ct, header->rte_waypt_ct(), segment_ct);
+ if (opt_debug) {
+ gbDebug("%s %d ct: %d, waypt_count: %d, segments %d\n", segment_type, header->rte_num, point_ct, header->rte_waypt_ct(), segment_ct);
}
- if (!debug && (point_ct != header->rte_waypt_ct())) {
- fatal(MYNAME ":%s %d count mismatch, expected %d, actual %d\n", segment_type, header->rte_num, header->rte_waypt_ct(), point_ct);
+ if (!opt_debug && (point_ct != header->rte_waypt_ct())) {
+ gbFatal("%s %d count mismatch, expected %d, actual %d\n", segment_type, header->rte_num, header->rte_waypt_ct(), point_ct);
}
}
RteHdFunctor<ValidateFilter> validate_head_f(this, &ValidateFilter::validate_head);
RteHdFunctor<ValidateFilter> validate_head_trl_f(this, &ValidateFilter::validate_head_trl);
- debug = opt_debug;
- checkempty = opt_checkempty;
-
point_ct = 0;
- if (debug) {
- fprintf(stderr, "\nProcessing waypts\n");
+ if (opt_debug) {
+ gbDebug("\nProcessing waypts\n");
}
waypt_disp_all(validate_point_f);
- if (debug) {
- fprintf(stderr, "point ct: %d, waypt_count: %d\n", point_ct, waypt_count());
+ if (opt_debug) {
+ gbDebug("point ct: %d, waypt_count: %d\n", point_ct, waypt_count());
}
- if (!debug && (point_ct != waypt_count())) {
- fatal(MYNAME ":Waypoint count mismatch, expected %d, actual %d\n", waypt_count(), point_ct);
+ if (!opt_debug && (point_ct != waypt_count())) {
+ gbFatal("Waypoint count mismatch, expected %d, actual %d\n", waypt_count(), point_ct);
}
head_ct = 0;
total_point_ct = 0;
total_segment_ct = 0;
segment_type = "route";
- if (debug) {
- fprintf(stderr, "\nProcessing routes\n");
+ if (opt_debug) {
+ gbDebug("\nProcessing routes\n");
}
route_disp_all(validate_head_f, validate_head_trl_f, validate_point_f);
- if (debug) {
- fprintf(stderr, "route head ct: %d, route_count: %d, total segment count: %d\n", head_ct, route_count(), total_segment_ct);
- fprintf(stderr, "total route point ct: %d, route_waypt_count: %d\n", total_point_ct, route_waypt_count());
+ if (opt_debug) {
+ gbDebug("route head ct: %d, route_count: %d, total segment count: %d\n", head_ct, route_count(), total_segment_ct);
+ gbDebug("total route point ct: %d, route_waypt_count: %d\n", total_point_ct, route_waypt_count());
}
- if (!debug && (head_ct != route_count())) {
- fatal(MYNAME ":Route count mismatch, expected %d, actual %d\n", route_count(), head_ct);
+ if (!opt_debug && (head_ct != route_count())) {
+ gbFatal("Route count mismatch, expected %d, actual %d\n", route_count(), head_ct);
}
- if (!debug && (total_point_ct != route_waypt_count())) {
- fatal(MYNAME ":Total route waypoint count mismatch, expected %d, actual %d\n", route_waypt_count(), total_point_ct);
+ if (!opt_debug && (total_point_ct != route_waypt_count())) {
+ gbFatal("Total route waypoint count mismatch, expected %d, actual %d\n", route_waypt_count(), total_point_ct);
}
head_ct = 0;
total_point_ct = 0;
total_segment_ct = 0;
segment_type = "track";
- if (debug) {
- fprintf(stderr, "\nProcessing tracks\n");
+ if (opt_debug) {
+ gbDebug("\nProcessing tracks\n");
}
track_disp_all(validate_head_f, validate_head_trl_f, validate_point_f);
- if (debug) {
- fprintf(stderr, "track head ct: %d, track_count: %d, total segment count: %d\n", head_ct, track_count(), total_segment_ct);
- fprintf(stderr, "total track point ct: %d, track_waypt_count: %d\n", total_point_ct, track_waypt_count());
+ if (opt_debug) {
+ gbDebug("track head ct: %d, track_count: %d, total segment count: %d\n", head_ct, track_count(), total_segment_ct);
+ gbDebug("total track point ct: %d, track_waypt_count: %d\n", total_point_ct, track_waypt_count());
}
- if (!debug && (head_ct != track_count())) {
- fatal(MYNAME ":Track count mismatch, expected %d, actual %d\n", track_count(), head_ct);
+ if (!opt_debug && (head_ct != track_count())) {
+ gbFatal("Track count mismatch, expected %d, actual %d\n", track_count(), head_ct);
}
- if (!debug && (total_point_ct != track_waypt_count())) {
- fatal(MYNAME ":Total track waypoint count mismatch, expected %d, actual %d\n", track_waypt_count(), total_point_ct);
+ if (!opt_debug && (total_point_ct != track_waypt_count())) {
+ gbFatal("Total track waypoint count mismatch, expected %d, actual %d\n", track_waypt_count(), total_point_ct);
}
- if (checkempty) {
+ if (opt_checkempty) {
if (waypt_count()==0 && route_waypt_count()==0 && track_waypt_count()==0) {
- fatal(MYNAME ":No input\n");
+ gbFatal("No input\n");
}
}
}
private:
OptionBool opt_debug;
- bool debug{};
OptionBool opt_checkempty;
- bool checkempty{};
int point_ct{};
int total_point_ct{};
int segment_ct{};
#include "geocache.h" // for Geocache, Geocache::UtfString
-#define MYNAME "VCF"
-
-
void
VcfFormat::wr_init(const QString& fname)
{
- file_out = gbfopen(fname, "w", MYNAME);
+ file_out = gbfopen(fname, "w");
}
void
#include <type_traits> // for is_base_of
#include <utility> // for as_const
-#include "defs.h" // for arglist_t, CSTR, fatal, ff_cap, ARGTYPE_TYPEMASK, ff_type, ARGTYPE_BOOL, case_ignore_strcmp, gpsdata_type, warning, ff_cap_array, global_options, global_opts, ARGTYPE_FLOAT, ARGTYPE_HIDDEN, ARGTYPE_INT, ARGTYPE_REQUIRED
+#include "defs.h" // for arglist_t, CSTR, gbFatal, ff_cap, ARGTYPE_TYPEMASK, ff_type, ARGTYPE_BOOL, case_ignore_strcmp, gpsdata_type, gbWarning, ff_cap_array, global_options, global_opts, ARGTYPE_FLOAT, ARGTYPE_HIDDEN, ARGTYPE_INT, ARGTYPE_REQUIRED
#include "dg-100.h" // for Dg100FileFormat, Dg100SerialFormat, Dg200FileFormat, Dg200SerialFormat
#include "exif.h" // for ExifFormat
#include "format.h" // for Format
QString id = QStringLiteral("%1(%2)").arg(module, arg.argstring);
if (arg.argval == nullptr) {
- fatal("%s: Program error - No local variable defined for option.\n", qPrintable(id));
+ gbFatal("%s: Program error - No local variable defined for option.\n", gbLogCStr(id));
}
arg.argval->reset();
rval = '1';
}
} else {
- warning("%s: Invalid logical value \"%s\".\n", qPrintable(id), qPrintable(val));
+ gbWarning("%s: Invalid logical value \"%s\".\n", gbLogCStr(id), gbLogCStr(val));
rval = '0';
}
}
if (args) {
for (const auto& arg : *args) {
if ((arg.argval != nullptr) && !arg.argval->isEmpty()) {
- printf("options: module/option=value: %s/%s=\"%s\"",
- qPrintable(vecname), qPrintable(arg.argstring), qPrintable(arg.argval->get()));
+ gbDebug("options: module/option=value: %s/%s=\"%s\"",
+ gbLogCStr(vecname), gbLogCStr(arg.argstring), gbLogCStr(arg.argval->get()));
if (case_ignore_strcmp(arg.defaultvalue, arg.argval->get()) == 0) {
- printf(" (=default)");
+ gbDebug(" (=default)");
}
- printf("\n");
+ gbDebug("\n");
}
}
}
}
}
if (!valid) {
- warning("'%s' is an unknown option to %s.\n", qPrintable(option_name), qPrintable(name));
+ gbWarning("'%s' is an unknown option to %s.\n", gbLogCStr(option_name), gbLogCStr(name));
}
}
}
{
QStringList options = fmtargstring.split(',');
if (options.isEmpty()) {
- fatal("A format name is required.\n");
+ gbFatal("A format name is required.\n");
}
const QString fmtname = options.takeFirst();
QString styledir(":/style");
QDir dir(styledir);
if (!dir.isReadable()) {
- fatal(FatalMsg() << "style directory" << QFileInfo(styledir).absoluteFilePath() << "not readable.");
+ gbFatal(FatalMsg() << "style directory" << QFileInfo(styledir).absoluteFilePath() << "not readable.");
}
dir.setNameFilters(QStringList("*.style"));
QVector<style_vec_t> slist;
for (const auto& fileinfo : fileinfolist) {
if (!fileinfo.isReadable()) {
- fatal(FatalMsg() << "Cannot open style file" << fileinfo.absoluteFilePath() << ".");
+ gbFatal(FatalMsg() << "Cannot open style file" << fileinfo.absoluteFilePath() << ".");
}
style_vec_t entry;
void
waypt_status_disp(int total_ct, int myct)
{
- fprintf(stdout, "%d/%d/%d\r", myct*100/total_ct, myct, total_ct);
- fflush(stdout);
+ // If we use logging the first update will have this info trailing the
+ // "id: " output by qFormatLogMessage but subsequent updates will not.
+ fprintf(stderr, "%d/%d/%d\r", myct*100/total_ct, myct, total_ct);
+ fflush(stderr);
}
void
}
if ((this->latitude < -90) || (this->latitude > 90.0))
- fatal(FatalMsg() << this->session->name
+ gbFatal(FatalMsg() << this->session->name
<< "Invalid latitude" << lat_orig << "in waypoint"
<< this->shortname);
if ((this->longitude < -180) || (this->longitude > 180.0))
- fatal(FatalMsg() << "Invalid longitude" << lon_orig << "in waypoint"
+ gbFatal(FatalMsg() << "Invalid longitude" << lon_orig << "in waypoint"
<< this->shortname);
}
#include "strptime.h" // for strptime
-#define MYNAME "XCSV"
-
const QHash<QString, XcsvStyle::xcsv_token> XcsvStyle::xcsv_tokens {
{ "ALT_FEET", XT_ALT_FEET },
{ "ALT_METERS", XT_ALT_METERS },
void XcsvStyle::validate_fieldmap(const field_map& fmp, bool is_output)
{
if (fmp.key.isEmpty()) {
- fatal(FatalMsg() << MYNAME << ": xcsv style is missing" <<
+ gbFatal(FatalMsg() << "xcsv style is missing" <<
(is_output ? "output" : "input") << "field type.");
}
if (fmp.val.isNull()) {
- fatal(FatalMsg() << MYNAME << ": xcsv style" << fmp.key.constData() << "is missing default.");
+ gbFatal(FatalMsg() << "xcsv style" << fmp.key.constData() << "is missing default.");
}
if (is_output && fmp.printfc.isNull()) {
- fatal(FatalMsg() << MYNAME << ": xcsv style" << fmp.key.constData() << "output is missing format specifier.");
+ gbFatal(FatalMsg() << "xcsv style" << fmp.key.constData() << "output is missing format specifier.");
}
}
bad_time_parse = true;
}
if ((time_result.has_value() && !time_result->isValid()) || bad_time_parse) {
- fatal(MYNAME ": couldn't parse time from string '%s' with format '%s'.\n",
+ gbFatal("couldn't parse time from string '%s' with format '%s'.\n",
s, format);
}
if (time_result.has_value()) {
bad_date_parse = true;
}
if ((date_result.has_value() && !date_result->isValid()) || bad_date_parse) {
- fatal(MYNAME ": couldn't parse date from string '%s' with format '%s'.\n",
+ gbFatal("couldn't parse date from string '%s' with format '%s'.\n",
s, format);
}
if (date_result.has_value()) {
} else {
// Don't fuss for empty strings.
if (*s) {
- warning("date parse of string '%s' with format '%s' failed.\n",
+ gbWarning("date parse of string '%s' with format '%s' failed.\n",
s, format);
}
}
Geocache* gc_data = nullptr;
if (fmp.printfc.isNull()) {
- fatal(MYNAME ": xcsv style '%s' is missing format specifier", fmp.key.constData());
+ gbFatal("xcsv style '%s' is missing format specifier\n", fmp.key.constData());
}
if (0 == strcmp(fmp.printfc.constData(), "\"%s\"")) {
} else if (*s == 's' || *s == 'S') {
parse_data->lat_dir_positive = false;
} else {
- warning("parse of string '%s' on line number %d as LAT_DIR failed. Expected 'n', 'N', 's' or 'S'.\n", s, line_no);
+ gbWarning("parse of string '%s' on line number %d as LAT_DIR failed. Expected 'n', 'N', 's' or 'S'.\n", s, line_no);
}
break;
case XcsvStyle::XT_LON_DIR:
} else if (*s == 'w' || *s == 'W') {
parse_data->lon_dir_positive = false;
} else {
- warning("parse of string '%s' on line number %d as LON_DIR failed. Expected 'e', 'E', 'w' or 'W'.\n", s, line_no);
+ gbWarning("parse of string '%s' on line number %d as LON_DIR failed. Expected 'e', 'E', 'w' or 'W'.\n", s, line_no);
}
break;
/* SPECIAL COORDINATES/GRID */
case XcsvStyle::XT_MAP_EN_BNG:
parse_coordinates(s, kDatumOSGB36, grid_bng,
- &wpt->latitude, &wpt->longitude, MYNAME);
+ &wpt->latitude, &wpt->longitude);
break;
case XcsvStyle::XT_UTM_ZONE:
parse_data->utm_zone = xstrtoi(s, nullptr, 10);
wpt->SetCreationTime(0, excel_to_timetms(et));
parse_data->need_datetime = false;
} else if (!value.isEmpty()) {
- warning("parse of string '%s' on line number %d as EXCEL_TIME failed.\n", s, line_no);
+ gbWarning("parse of string '%s' on line number %d as EXCEL_TIME failed.\n", s, line_no);
}
}
break;
wpt->SetCreationTime(tt);
parse_data->need_datetime = false;
} else if (!value.isEmpty()) {
- warning("parse of string '%s' on line number %d as TIMET_TIME failed.\n", s, line_no);
+ gbWarning("parse of string '%s' on line number %d as TIMET_TIME failed.\n", s, line_no);
}
}
break;
wpt->SetCreationTime(0, tt);
parse_data->need_datetime = false;
} else if (!value.isEmpty()) {
- warning("parse of string '%s' on line number %d as TIMET_TIME_MS failed.\n", s, line_no);
+ gbWarning("parse of string '%s' on line number %d as TIMET_TIME_MS failed.\n", s, line_no);
}
}
break;
wpt->SetCreationTime(dotnet_time_to_qdatetime(dnt));
parse_data->need_datetime = false;
} else if (!value.isEmpty()) {
- warning("parse of string '%s' on line number %d as NET_TIME failed.\n", s, line_no);
+ gbWarning("parse of string '%s' on line number %d as NET_TIME failed.\n", s, line_no);
}
}
break;
} else if (strncmp(fmp.key.constData(), "LAT_10E", 7) == 0) {
wpt->latitude = strtod(s, nullptr) / pow(10.0, strtod(fmp.key.constData()+7, nullptr));
} else {
- warning(MYNAME ": Unknown style directive: %s\n", fmp.key.constData());
+ gbWarning("Unknown style directive: %s\n", fmp.key.constData());
}
break;
default:
- fatal("Unknown style directive: %s - %d\n", fmp.key.constData(), fmp.hashed_key);
+ gbFatal("Unknown style directive: %s - %d\n", fmp.key.constData(), fmp.hashed_key);
break;
}
}
xcsv_style->field_encloser, linecount);
if (xcsv_style->ifields.isEmpty()) {
- fatal(MYNAME ": attempt to read, but style '%s' has no IFIELDs in it.\n", qPrintable(xcsv_style->description)? qPrintable(xcsv_style->description) : "unknown");
+ gbFatal("attempt to read, but style '%s' has no IFIELDs in it.\n", gbLogCStr(xcsv_style->description)? gbLogCStr(xcsv_style->description) : "unknown");
}
int ifield_idx = 0;
double north;
double east;
if (! GPS_Math_WGS84_To_UKOSMap_H(wpt->latitude, wpt->longitude, &east, &north, map))
- fatal(MYNAME ": Position (%.5f/%.5f) outside of BNG.\n",
+ gbFatal("Position (%.5f/%.5f) outside of BNG.\n",
wpt->latitude, wpt->longitude);
buff = QString::asprintf(fmp.printfc.constData(), map, qRound(east), qRound(north));
}
}
break;
default:
- warning(MYNAME ": Unknown style directive: %s\n", fmp.key.constData());
+ gbWarning("Unknown style directive: %s\n", fmp.key.constData());
break;
}
QString obuff = csv_stringclean(buff, xcsv_style->badchars);
} else if (p == u"WAYPOINT") {
style->datatype = wptdata;
} else {
- fatal(FatalMsg() << MYNAME << ": Unknown data type" << p);
+ gbFatal(FatalMsg() << "Unknown data type" << p);
}
} else if (op == u"IFIELD") {
if (tokens.size() < 3) {
- fatal(FatalMsg() << "Invalid IFIELD line: " << tokenstr);
+ gbFatal(FatalMsg() << "Invalid IFIELD line: " << tokenstr);
}
// The key ("LAT_DIR") should never contain quotes.
unsigned options = 0;
// Note: simplified() has to run after split().
if (tokens.size() < 3) {
- fatal(FatalMsg() << "Invalid OFIELD line: " << tokenstr);
+ gbFatal(FatalMsg() << "Invalid OFIELD line: " << tokenstr);
}
// The key ("LAT_DIR") should never contain quotes.
XcsvStyle style;
gpsbabel::TextStream stream;
- stream.open(fname, QIODevice::ReadOnly, MYNAME);
+ stream.open(fname, QIODevice::ReadOnly);
QString sbuff;
while (stream.readLineInto(&sbuff)) {
xcsv_parse_style_line(&style, sbuff.trimmed());
xcsv_style = new XcsvStyle(XcsvStyle::xcsv_read_style(intstylefile));
} else {
if (!styleopt) {
- fatal(MYNAME ": XCSV input style not declared. Use ... -i xcsv,style=path/to/file.style\n");
+ gbFatal("XCSV input style not declared. Use ... -i xcsv,style=path/to/file.style\n");
}
xcsv_style = new XcsvStyle(XcsvStyle::xcsv_read_style(styleopt));
if ((xcsv_style->datatype == 0) || (xcsv_style->datatype == wptdata)) {
if (global_opts.masked_objective & (TRKDATAMASK|RTEDATAMASK)) {
- warning(MYNAME " attempt to read %s as a track or route, but this format only supports waypoints on read. Reading as waypoints instead.\n", qPrintable(fname));
+ gbWarning("attempt to read %s as a track or route, but this format only supports waypoints on read. Reading as waypoints instead.\n", gbLogCStr(fname));
}
}
xcsv_file = new XcsvFile;
if (xcsv_style->codecname.isEmpty()) {
- xcsv_file->stream.open(fname, QIODevice::ReadOnly, MYNAME);
+ xcsv_file->stream.open(fname, QIODevice::ReadOnly);
} else {
- xcsv_file->stream.open(fname, QIODevice::ReadOnly, MYNAME, CSTR(xcsv_style->codecname));
+ xcsv_file->stream.open(fname, QIODevice::ReadOnly, CSTR(xcsv_style->codecname));
}
xcsv_file->fname = fname;
}
xcsv_file->gps_datum_idx = GPS_Lookup_Datum_Index(datum_name);
if (xcsv_file->gps_datum_idx < 0) {
- fatal(MYNAME ": datum \"%s\" is not supported.", qPrintable(datum_name));
+ gbFatal("datum \"%s\" is not supported.\n", gbLogCStr(datum_name));
}
utc_offset = opt_utc? opt_utc.get_result() * SECONDS_PER_HOUR : 0;
xcsv_style = new XcsvStyle(XcsvStyle::xcsv_read_style(intstylefile));
} else {
if (!styleopt) {
- fatal(MYNAME ": XCSV output style not declared. Use ... -o xcsv,style=path/to/file.style\n");
+ gbFatal("XCSV output style not declared. Use ... -o xcsv,style=path/to/file.style\n");
}
xcsv_style = new XcsvStyle(XcsvStyle::xcsv_read_style(styleopt));
xcsv_file = new XcsvFile;
if (xcsv_style->codecname.isEmpty()) {
- xcsv_file->stream.open(fname, QIODevice::WriteOnly | QIODevice::Text, MYNAME);
+ xcsv_file->stream.open(fname, QIODevice::WriteOnly | QIODevice::Text);
} else {
- xcsv_file->stream.open(fname, QIODevice::WriteOnly | QIODevice::Text, MYNAME, CSTR(xcsv_style->codecname));
+ xcsv_file->stream.open(fname, QIODevice::WriteOnly | QIODevice::Text, CSTR(xcsv_style->codecname));
}
xcsv_file->fname = fname;
}
xcsv_file->gps_datum_idx = GPS_Lookup_Datum_Index(datum_name);
if (xcsv_file->gps_datum_idx < 0) {
- fatal(MYNAME ": datum \"%s\" is not supported.", qPrintable(datum_name));
+ gbFatal("datum \"%s\" is not supported.\n", gbLogCStr(datum_name));
}
}
//#include <QtCore> // for QHash, QIODeviceBase::ReadOnly
#include <QtGlobal> // for qPrintable
-#include "defs.h" // for fatal
+#include "defs.h" // for gbFatal
#include "src/core/file.h" // for File
-#define MYNAME "XML Reader"
-
/***********************************************************************
* These implement a simple interface for "generic" XML that
* maps reasonably close to 1:1 between XML tags and internal data
if (encoding != nullptr) {
codec = QTextCodec::codecForName(encoding);
if (codec == nullptr) {
- fatal(MYNAME " : codec \"%s\" is not available.\n", encoding);
+ gbFatal("codec \"%s\" is not available.\n", encoding);
}
} else {
codec = QTextCodec::codecForName("UTF-8");
xml_run_parser(reader);
if (reader.hasError()) {
- fatal(MYNAME " :Read error: %s (%s, line %lld, col %lld)\n",
- qPrintable(reader.errorString()),
- qPrintable(file.fileName()),
+ gbFatal("Read error: %s (%s, line %lld, col %lld)\n",
+ gbLogCStr(reader.errorString()),
+ gbLogCStr(file.fileName()),
reader.lineNumber(),
reader.columnNumber());
}
xml_run_parser(reader);
if (reader.hasError()) {
- fatal(MYNAME " :Read error: %s (%s, line %lld, col %lld)\n",
- qPrintable(reader.errorString()),
+ gbFatal("Read error: %s (%s, line %lld, col %lld)\n",
+ gbLogCStr(reader.errorString()),
"unknown",
reader.lineNumber(),
reader.columnNumber());